CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

Defensive copies

Rule five in action.

An immutable class can be broken from outside if it keeps a caller's mutable object. EJ Item 50 shows a time period class whose fields are final and private, but built on the mutable Date. The caller keeps a reference to the date and changes it later, and the period changes with it.

The same problem appears with a list of guests.

final class BrokenGuests {                       // looks immutable, is not
    private final List<String> names;
    BrokenGuests(List<String> n) { names = n; }
    List<String> names() { return names; }
}

final class Guests {                             // safe
    private final List<String> names;
    Guests(List<String> n) { names = List.copyOf(n); }
    List<String> names() { return names; }
    Guests with(String extra) {
        List<String> l = new ArrayList<>(names);
        l.add(extra);
        return new Guests(l);
    }
}

Start with a list holding asha and ravi. Build both objects from it, then add "intruder" to the original list. BrokenGuests now reports three names. Guests still reports asha and ravi. List.copyOf made an unmodifiable copy at the door, so later changes to the caller's list do not reach it. Calling add on Guests.names() throws UnsupportedOperationException, so the accessor can hand out the list without a second copy.

EJ makes two points about the order of work. Copy first, then validate the copy, since another thread might change the original between the check and the copy. And copy in accessors too, when the field is mutable and no read-only view is available.

The with method is the immutable way to "change" a value. g.with("meera") returns a new Guests of three names, and g still has two. Such methods are often called wither methods, and they are how a builder-like step looks for a value (see Level 3, module 3).

Prefer immutable types from the start. EJ recommends Instant and the other java.time classes over Date for this reason. Defensive copying is the fix for the cases where a mutable type cannot be avoided.

Common mistake

Marking a field final and believing the object is immutable. final fixes the reference, not the thing it points to. A final list can still be changed.

Check yourself: 1. After the caller adds "intruder", what does each class report? 2. Why does EJ copy before validating? 3. What does with return, and what happens to the original?