Author Archives: Maciej Dzikowicki

Java Interview Questions – contract between equals and hashCode

Question about contract between equals and hashCode is one of the most common question on interviews for Java developers. Let’s see how somebody should answer and what implications this contract has.

First look at this example:

This example can explain a lot. First of all string a and b are not equal, but their hashCode are the same.

That means that contract for equals and hashCode is:

  • when two objects are equal, their hashCode must be the same,
  • when two objects has the same hashCode, they don’t have to be equal.

Follow up questions

  1. Is hashCode implementation that returns constant value correct?

This is correct implementation but should be avoided because using such objects as keys in HashMap gives performance issues.

  1. How does HashMap handle objects with the same hashCode?

HashMap puts those keys to buckets and than it is using equals to find proper key.

Java 8 – Streams API instead of FluentIterable

In one of my recent posts I was comparing FluentIterable with Java 8 Lambdas (here). Now let’s take a look at how Streams API introduced in Java 8 changed way we write code.

What is Streams API?

Streams are not Collections. Streams are lazy data structures that compute values on demand. It is important to know that Streams have two types of operations:

  • intermediate – those operations return stream and can be combined into pipeline. For example filter, map, etc
  • terminal – those operations returns final result. For example sum, count, etc.

So lets start usage of Streams API with some POJO class.

Now imagine case where we want to calculate count of items which name ends with “C”.

As you can see in this example code written with Streams API is very readable. I added comments, but basically you can read code as normal sentences. Moreover it has big advantage over Guava implementation because you don’t have to create inner class implementing Predicate and Function interfaces.

Also it is easier to create new collection based on results of pipeline processing by using Collectors.

As you can see from this two examples Streams API is very easy to use and makes code really clean. It changes way of writing code from imperative to declarative.

More to read

UTC dates handling in AngularJS applications

Almost every developer sooner or later is facing issues with dates. It may be formatting, timezones, etc. I would like to describe few tips about dates handling in AngularJS applications.

Using date filter

If you know, that some model field is native date object you can tell Angular to display it as date in UTC timezone. This is important, because in Javascript native dates are always in user’s local timezone. This is usually helpful when we need to display dates received from REST services, which most often are in UTC.

{{ ::model.someDate | date : 'dd/MM/yyyy' : 'UTC'}}

Using ngModelOptions

Using ngModelOptions is very helpful when you need to create input and allow users to set some date. The issue here is that when user enters date for the first time, everything is fine. But after storing it in backend, and receiving it back as date in UTC, you can have issues with differences between dates. In order to fix that Angular (from 1.3.0) has ng-model-options directive.

 <input
	id="someDate"
	name="someDate"
	type="date"
	ng-model="someDate"                            
	ng-model-options="{timezone: 'UTC'}">

Creating new date in UTC

New Date object created by new Date() will be in local timezone. If you want to create Date object in UTC timezone, you can use following service (it requires moment.js):

'use strict';

angular.module('dates').service('UtcDate', [
  function() {
    var UtcDate = function() {

    };

    UtcDate.prototype.getCurrentMomentUTC = function() {
      var date = new Date();
      return moment.utc(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
    };

    return new UtcDate();
  }
]);

Announcing card.js

I would like to announce card.js!

It is brand new library with following features:

  • Credit card type detection based on IIN number. See more on wikipedia.
  • Credit card type detection for full length card number
  • Luhn algorithm validation. See more on wikipedia.

How to use it?

It can be loaded via a script tag in a HTML document for the browser (check examples/browser)

<script src='./relative/path/to/card.js'></script>

or as a CommonJS module.

For Node, put the card.js file into the same directory as the file that is requiring it and use

var card = require('./card.js');

or put it in a node_modules directory within the directory and use require(‘card.js’). See example in examples/nodejs.

The library is also available from the npm registry, so

$ npm install card.js

will install this library in a node_modules directory within the current directory.

Example of usage

card('4111111111111111').getType(); // output: visa
card('41').getIINType(); // output: visa
card('4111111111111111').isValid(); // output: true

Supported browsers:

  • Chrome
  • Firefox
  • Internet Explorer 9
  • Safari
  • Opera

Supported card types:

Issuing network card type returned by getType
Visa visa
Mastercard mastercard
American Express amex
Maestro meastro
Diners Club diners
Discover discover
JCB jcb
UATP uatp
InterPayment interpayment
InstaPayment instapayment
China UnionPay unionpay
Dankort dankort

AngularJS: testing keydown listener

Working with AngularJS is really great experience. This framework comes with many handy features. One of them is build-in support for unit testing. In this post I want to show how to test keydown event listener.

I was recently working on performing some action when user press ESC key. Basically implementation is easy:

angular.module('app').directive('handleEsc', [
  '$document',
  function (
    $document
  ) {
    var ESC_KEY_CODE = 27;

    return {
      scope: {
        handleEsc: '&'
      },
      link: function (scope, element, attrs) {
        /**
         * Create handler for keydown event
         */
        function escHandler (event) {
          if (event.keyCode === ESC_KEY_CODE) {
            scope.handleEsc();
          }
        }

        /**
         * Attach handler to event
         */
        $document.on('keydown', escHandler);

        /**
         * Clean on destroy
         */
        scope.$on('$destroy', function () {
          $document.off('keydown', escHandler);
        });
      }
    };
  }
]);

So what this code is doing? First of all it creates isolated scope with binding method from parent scope by using &. Then in link function it is defining handler for keydown event and attaching this to document. In such cases it is necessary to unregister listener when in order to prevent memory leakage and this is done on scope destroy event.

Now lets move to the interesting part!

Testing keydown

I was looking for solution for a really long time. Finally my more experienced friends helped me.

'use strict';

describe('Directive: handleEsc', function() {
  var scope;
  var $compile;
  var $document;

  beforeEach(angular.mock.module('app'));

  var element = null;
  /**
   * Lets call scope.close() method on ESC key event
   */
  var template = '<div handle-esc="close()"></div>';

  beforeEach(inject(function($injector) {
    $compile  = $injector.get('$compile');
    scope     = $injector.get('$rootScope').$new();
    $document = $injector.get('$document');
  }));

  beforeEach(function() {
    element = $compile(template)(scope);
    /**
     * Create method and spyOn it.
     */
    scope.close = function() {};
    spyOn(scope, 'close');
  });

  function triggerEscKeyDown() {
    /**
     * Create KeyboardEvent
     */
    var e = new window.KeyboardEvent('keydown', {
      bubbles: true,
      cancelable: true,
      shiftKey: true
    });

    /**
     * Assing 27 as keyCode
     */
    delete e.keyCode;
    Object.defineProperty(e, 'keyCode', {'value': 27});

    $document[0].dispatchEvent(e);
  }

  it('should call callback function when the event happens', function() {
    triggerEscKeyDown();
    expect(scope.close).toHaveBeenCalled();
  });

  it('deregisters on scope $destroy', function() {
    scope.$destroy();
    triggerEscKeyDown();
    expect(scope.close).not.toHaveBeenCalled();
  });

});

As you can see in this test I had to use native KeyboardEvent in order to test my directive. As was not able to find any other working example with test for keydown listener. If you know other solution please share in comments.