Tuesday, July 28, 2015

Immutability in Java - What it takes to build an immutable class


Immutability means something that cannot be changed. In java an immutable class is one whose state cannot be changed once it has been created. This post aims to give a guideline on how to make a class immutable. The post contains an example of creating an immutable class.
The complete code is available on Github

The Java documentation gives a list of guidelines for creating an immutable class. We will try to understand it better.

To make a class immutable, follow the following steps:
  1. Declare the class as final. 
  2. Make all its fields final and private.
  3. For all mutable fields, make sure that the class creates a copy and only returns the copy to the calling code.
  4. Do not provide any setter methods.

Let's try to understand why we need to do all of the above for making a class immutable. We need to ensure that the subclasses do not override any of the class methods. Declaring the class as final ensures that the class cannot be overridden. A more sophisticated approach is to make the constructor private and use a factory method to create an instance of the class. Making all the fields private will ensure that the fields cannot be changed outside the class, and making them final will ensure that we do not alter the field even by mistake. For all the mutable fields, we are making sure that no other object from outside can change the data by creating a defensive copy of the object and only returning this copy to the calling code. Setter methods are usually used to change the state of the object and as the goal of an immutable class is to avoid state changes, hence we do not provide any setter methods.

Lets look at an example of Immutable class:



We have three fields in the class, first field of Integer type, second field of String type, and third field of Date type. The String and Integer classes are immutable, however the Date class is mutable. Thus, we create a new Date object when assigning the Date to the class field.
That's all for immutability.


Reference: Java Documentation

Tuesday, July 14, 2015

Getting Started with TestNG

TestNG is a testing framework which, inspired by JUnit and NUnit, but introduces things like dependency testing, grouping concept to make testing more powerful and easier to do. It is designed to cover all categories of tests: unit, functional, end-to-end, integration, etc...
The NG in TestNG stands for Next Generation. TestNG requires JDK7 or higher.
Reference: http://testng.org/doc/index.html

In this post, we will be discussing how to use TestNG to write a simple test:

Firstly, add the TestNG library in the pom.xml


Lets create a simple Java class that has a method that returns the String passed to it.


Create a test case like this:


Thats it, a simple TestNG test case is created.