Notes
The problem
Here is the bug. A cart has two lines, tea and chai, and both were built with the same price object for two hundred rupees. Later a promotion takes ten percent off tea, by calling set amount on tea's price. But that is the very same object chai holds. Chai's price silently changes to one hundred and eighty as well. Nothing looks wrong at the call site. This is aliasing, two references to one mutable object.
MutablePrice p = new MutablePrice(200);
CartLine tea = new CartLine("tea", p);
CartLine chai = new CartLine("chai", p);
// ten percent off tea only
tea.price().setAmount(180);
chai.price().amount(); // 180 too! The idea
An immutable object gets all its state in the constructor and never changes after that. The rules are simple. Make every field private and final. Add no setters. Stop subclasses from adding mutable state, by making the class final. Check the values in the constructor. Copy any mutable input, like a list, and never hand out your internal list. To change something, return a brand new object instead.
- • all fields private final
- • no setters
- • class cannot be extended
- (final, or a record)
- • validate in the constructor
- • copy mutable inputs in,
- never hand internals out
- • "change" = return a NEW
- object
Value objects
A value object is an object defined only by its values, like a number. Two Money objects of two hundred rupees are equal, and you can swap one for the other without anyone noticing. Dates, addresses and amounts are value objects, and they should be immutable. An entity is different. Booking B seventy seven keeps its identity even when its dates change. Entities can change, but they are built out of immutable values.
- value object: no identity
- two 200 INR notes are
- equal; swap them freely
- Money, StayDates, Address
- entity: has an identity
- that stays while data
- changes
- Booking #B-77, a Guest
Records
Java records are made for this. Declaring record Money with an amount and a currency gives you private final fields, accessor methods, and equals, hash code and to string based on the values. The compact constructor is where you validate, for example no negative amounts. Arithmetic like plus never changes this object. It checks the currencies match and returns a new Money. Amounts are stored in paise, as a long, so there is no floating point error.
record Money(long minor, String currency) {
Money {
if (minor < 0)
throw new IllegalArgumentException();
}
Money plus(Money o) {
sameCurrency(o);
return new Money(minor + o.minor,
currency);
}
} The fix
Back to the cart, with an immutable Money. To discount tea, we ask its price for a new Money that is ten percent lower, and give tea a new line with that price. The original two hundred rupee object is untouched, so chai still costs two hundred. Sharing one Money between many lines is now completely safe, and even saves memory. The bug from the start of the lesson cannot be written any more.
Defensive copies
A trap: final only stops you from pointing the field at another list. It does not stop someone from adding to the list itself. If HotelBooking just stored the caller's list, the caller could add a guest later and the booking would change behind its back. So copy it in the constructor with List dot copy of. That copy is also unmodifiable, so returning it from the getter is safe. Records with a list field need the same copy in their compact constructor.
final class HotelBooking {
private final List<String> guests;
HotelBooking(List<String> guests, ...) {
this.guests = List.copyOf(guests);
}
List<String> guests() {
return guests; // already read-only
}
} Copy vs view
Be careful with the older helper, Collections dot unmodifiable list. It returns a read-only view over the original list. You cannot change it through the view, but if the original list changes, the view shows the change. List dot copy of makes a real snapshot instead, which is what an immutable object needs. Also remember that records are only shallowly immutable: a record holding a mutable list is not immutable unless you copy it.
List<String> src = new ArrayList<>();
var view = Collections
.unmodifiableList(src);
var copy = List.copyOf(src);
src.add("Ravi");
view.size(); // 1: sees the change
copy.size(); // 0: a real snapshot Changing a value
How do you change an immutable value? You do not. You build a new one. A with method returns a copy with one field different. StayDates with out returns new dates with a later checkout. Because every new object goes through the constructor, the rule that checkout must be after check-in is checked every time. A mutable class with two setters could pass through an invalid state in between. An immutable one never can.
record StayDates(LocalDate in,
LocalDate out) {
StayDates {
if (!out.isAfter(in)) throw ...;
}
StayDates withOut(LocalDate d) {
return new StayDates(in, d);
}
} Equality by value
Value objects compare by value. Two Money objects of two hundred rupees are two different objects in memory, so comparing them with double equals is false, but equals is true, and a set holding one contains the other. Records do this for you. Immutability also matters for map keys. If a mutable key changes after it goes into a hash map, its hash code changes and the map can no longer find it. Immutable keys can never get lost.
var a = new Money(20000, "INR"); var b = new Money(20000, "INR"); a == b // false: two objects a.equals(b) // true: same value Set.of(a).contains(b) // true mutable keys in a HashMap can get lost when they change
Thread safety for free
Here is the bonus. Race conditions need two things: shared data and someone changing it. Immutable objects remove the second one. Many threads can read the same booking or the same Money at once, with no locks and no volatile. Java also guarantees that final fields set in the constructor are visible to other threads once the object is safely built. So immutable objects are thread safe for free, and easy to cache and share.
Costs and limits
There are costs. Every change creates a new object. For small values that is cheap, and the garbage collector handles short lived objects well, but rebuilding a huge structure in a tight loop can hurt. And some things really do change over time, like a booking moving from held to confirmed. Keep such entities mutable, but build them out of immutable values. Java's own String, LocalDate, Integer and BigDecimal are all immutable.
- each change makes a new
- object: fine for values,
- costly in tight loops over
- big structures
- entities change over time:
- keep them mutable but build
- them from immutable values
- Java has many already:
- String, LocalDate, Integer
In interviews
In a design round, make every small data type a record and say why. Ticket, Money and Vehicle are records, built once, compared by value and safe to share across gate threads. Then point out that only a few classes hold changing state, so that is exactly where locking is needed. Common mistakes are storing money as a double, and getters that return the internal mutable list.
- "Ticket, Money and Vehicle
- are records: built once,
- compared by value, safe to
- share across gate threads."
- "Only ParkingLot and Spot
- hold changing state, so
- that is where locking goes."
- mistakes: money as double,
- getters returning live lists