Member-only story
Effective Java! Minimize Mutability
Today’s topic is about mutability and the benefits we can get from making our value objects immutable. I think this is a great topic to go over as it’s pretty simple and can make many other parts of your application simpler as well. What a wonderful combination!
The concept of an immutable object is simple, it’s an object that cannot be modified once it is created. Java’s platform libraries have a few example of immutable classes such as String
, BigDecimal
, BigInteger
, and the boxed primitive types. So why would you choose to make something immutable? Isn't removing capabilities a bad thing? Well, as interestingly often turns out to be the case, removing the capability to do something actually can make other things much simpler and safer. Before jumping into what immutability gives us let's talk about how to make a class immutable.
- Don’t provide methods for mutating state: Often called mutators or setters.
- Ensure classes can’t be extended Most commonly accomplished by making the class final.
- Make all fields final: Clearly expresses desire that the internal state will not be mutated. Also assists when passing state from one thread to another.
- Make all fields private: You would likely being doing this if you are following other guidance from Effective Java and here we follow this guidance for all the same reasons.
- Ensure exclusive access to mutable state: If your immutable object provides mutable state via an accessor it…