Featured Post

Event Sourcing Video from Michael Ploed

Event Sourcing I want to share a great video I found few days ago that describes very well what Event Sourcing is.

Thursday, May 24, 2012

Immutable Objects

Immutable objects are objects whose state cannot change after construction. An Example of immutable objects from the JDK is the String class.

Immutable Objects Benefict

  • Thread-safe: there's no need of synchronization
  • Good Map keys

Immutable Object Guidelines

In order to create an immutable object:
  • Private constructors;
  • Avoid the Java Beans pattern creation (using set methods to inizialize);
  • Make fields private and final;
  • Make the class final;
  • Do not provide any methods which can change the state of the object;
  • Use defensively copied if the class has any mutable object fields.

The following class is an example of Immutable Class.

import java.util.Date;

public final class FootballMatch {

 private final Date matchDate;
 private final String place;
 private final String guestTeam;
 private final String homeTeam;

 public FootballMatch(Date matchDate, String place, String guestTeam,
   String homeTeam) {
  this.matchDate =  new Date(matchDate.getTime());
  this.place = place;
  this.guestTeam = guestTeam;
  this.homeTeam = homeTeam;

 public Date getMatchDate() {
  return new Date(this.matchDate.getTime());

 public String getPlace() {
  return place;

 public String getGuestTeam() {
  return guestTeam;

 public String getHomeTeam() {
  return homeTeam;


  1. Why class and fields are final, when we have only setters?

    1. Generally a class must be final in order to avoid subclassing in the future and to avoid consider again the immutability of you object.

      Fields should be final not just for external object reference modification (when you have setters), but to preserve the object reference inside your immutable object.
      It's not unusual to make mistakes with modifications on "field references" inside your presumed "immutable object"