Immutable Objects

At Codera we find we all share a common idea of what we believe to be "good" design. One facet of this is when we pass domain objects around our systems we generally like them to be immutable. 

So the first question is what does immutable mean? Simply, it means that once an object has been constructed its state can not be modified in anyway. No method call or operation should modify it.

Using Java as an example there are plenty number of immutable objects within the Standard JDK. A couple of the most prominent being java.lang.String and java.math.BigDecimal.

If you aren't used to immutable objects then it might seem a bit odd. If you had a BigDecimal that represented the number 5 then you might ask how you add 4 to it to get 9. 

The answer is quite simple. The BigDecimal class provides an add method that takes the number you want to add. Rather than modifying the instance the method is called on it returns a new instance of BigDecimal representing the answer.

In this case the code would look like:

    BigDecimal result = new BigDecimal("5").add(new BigDecimal("4"));

The instance assigned to result will have the value of 9.

Now that we know what immutable objects are why would we want to use them? 

One reason is it is safe to hand them out to callers of your code and not worry about their state being changed without your knowledge. 

An example of a mutable object in the Standard JDK that has been present since day 1 is java.util.Date. This has a whole host of set methods allowing you to change pretty much any field within the date. 

To understand why this is a problem imagine we had a class that represented a person and one of the fields was date of birth which used java.util.Date to hold the value.

A caller could use a method to retrieve the date of birth from the class and modify that object without calling a set method. This changes the persons date of birth without your code knowing about it. Obviously this is very bad and can lead to all sorts of problems. If calling code is modifying objects without your knowledge then failures can manifest much later in the program flow in strange ways that aren't easy to trace back to source. 

Mutable objects also tend not to be thread safe either. Another frustration of Java developers were the DateTimeFormatter and simliar APIs that were not threadsafe because they stored state internally. 

The issue of java.util.Date being mutable has been acknowledged and rectified in Java 8 with the introduction of a new api based on the Joda Time library. Both the Java 8 and Joda Time objects have immutable objects at the core of their design. 

Now that we have explained what immutable objects are the next article will look at how we can use the builder pattern to construct them more easily.