Immutability

In Object Orientation, an object is considered to be Immutable if its state cannot be modified once it has been created. As much as possible, ensure objects are Immutable.

This is also sometimes simplified to as “Don’t use setters”.

Rationale

Objects that are immutable are…

  • Easier to test
  • Thread/Concurrency safe
  • Void of side effects (i.e. execution will produce the same result each time)
  • Easier to cache
  • (possibly) safe to put in a Set or use as a key in a Map/Hash/Dictionary

Implications

  • Objects are only immmutable if there is no way to modify any of their properties after the object’s construction. Primitive types such as int, String are usually immutable but custom types and collections may not be.
  • Developers need to understand how immutablility is ensured in specific languages.

Examples

Example of mutable

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  class Person {
    private String name;
    private String emailAddress;

    public Person(String name, String emailAddress) {
      this.name = name;
      this.emailAddress = emailAddress;
    }
    public void changeEmailAddress(String emailAddress) {
      this.emailAddress = emailAddress;
    }
  }

Example of immutable

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  class Person {
    private final String name;
    private final String emailAddress;

    public Person(String name, String emailAddress) {
      this.name = name;
      this.emailAddress = emailAddress;
    }
    public Person changeEmailAddress(String emailAddress) {
      return new Person(this.name, emailAddress);
    }
  }

References