CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

Making a class immutable

Five rules, one reason each.

Think of a printed ticket. Once printed, it cannot be edited. If the seat changes, a new ticket is printed and the old one is thrown away. Everyone holding the ticket sees the same thing, and nobody needs to ask whether it changed.

EJ Item 17 defines an immutable class as one whose instances cannot be modified, with all information fixed for the life of the object. It gives five rules.

  1. Provide no methods that change state.
  2. Make the class impossible to extend, usually with final.
  3. Make every field final.
  4. Make every field private.
  5. Give the class exclusive access to any mutable part, so it never stores or returns a caller's reference to a mutable object.

Rule 2 stops a careless subclass from adding mutation. Rule 3 also matters for threads, because the Java memory model makes final fields safely visible once the constructor finishes. Rule 5 is the one people forget, and section 3 shows why.

A money class follows all five.

final class Money {
    static final Money ZERO = new Money(0, "INR");
    private final long paise; private final String currency;

    private Money(long paise, String currency) {
        this.paise = paise; this.currency = Objects.requireNonNull(currency);
    }
    static Money rupees(long r) { return new Money(r * 100, "INR"); }

    Money plus(Money o)  { check(o); return new Money(Math.addExact(paise, o.paise), currency); }
    Money times(int n)   { return new Money(Math.multiplyExact(paise, (long) n), currency); }
    private void check(Money o) {
        if (!currency.equals(o.currency)) throw new IllegalArgumentException("currency mismatch");
    }
    // equals, hashCode and toString omitted here, see Level 1 module 1
}

With a fee of 500 rupees (made up), fee.times(3).plus(Money.rupees(120)) is 1620.00. The variable fee is still 500.00 after that, because each call returned a new object. EJ calls this the functional approach, and notes that method names such as plus read as operations that make a value, where add suggests a change in place.

Money is held in whole paise as a long, not a double, so there is no rounding drift. addExact and multiplyExact throw on overflow, and the failure is loud and not silent.

Immutable class

An immutable class is a class whose objects cannot change after they are created. Operations return new objects.

Example: Money, where plus returns a new Money.

Check yourself: 1. Name the five rules. 2. What is fee after fee.times(3)? 3. Why is money held as paise in a long?