Java - Mutability

Introduction
It's easy to get blindsided in a safe programming language such as Java but there are security implications to consider, one of them being on the topic of mutability. Declaring classes and fields private is a great safety net to make any coder feel comfortable but with every net, there are holes to slip through.

Joshua Bloch did an excellent job on describing how to achieve immutable objects in his book Effective Java, second edition. Defiantly worth the read if you want to learn more on this subject (or about good coding standards in Java), along with great patterns and anti-patterns to dissect.

In Joshua's book he shares, 5 rules of immutability, which I provided in axiom from. Rehashing from earlier, pick up his book if you want to learn more the subject.

Mutable vs Immutable
A mutable object is an object that is capably of being change and likewise an immutable object is only capable of remaining constant with the value it was initialized with. A general rule of thumb is to immutable objects when every possible.

1. Don't provide any methods that modify the object's state
Anti-Pattern Example

// Causes this.obj to become mutable public void setObject(Object obj){ this.obj = obj }

2. Ensure that the class can't be extended
A simple way to follow this axiom is to declare the class as final.

private final class Foo{ private Foo{} }

3. Make all fields final
Note, the following code sample doesn't follow axiom 4.

private final class Foo{ public final static String placeHolder = "bar"; private Foo{} public final static String get{ return( placeHolder ); } }

4. Make all fields private
private final class Foo{ private final static String placeHolder = "bar"; private Foo{} public final static String get{ return( placeHolder ); } }

5. Ensure excursive access to any mutable components
It is generally wise to prevent clients from referencing mutable objects. To achieve this axiom, make defensive copies within constructors, accessors, and readObject methods. The following code sample was taken from Item 39 (Minus the class name and comments) from the second edition of Effective Java and will help guard against TOCTOU attacks. import java.util.Date; public final class AntiTOCTOU { private final Date start; private final Date end; // Defensive copy on parameters public AntiTOCTOU(Date start, Date end){ this.start = new Date( start.getTime ); this.end = new Date( end.getTime ); if(this.start.compareTo(end) > 0) throw new IllegalArgumentException(                this.start + " after " + this.end             ); }    // Defensive copies on accessors. public Date start{ return( new Date( start.getTime )); }    public Date end{ return( new Date( end.getTime )); } }