I'll Be Backend
Principles · Java

Immutability: value objects instead of setters

Share small objects like prices safely, so one change never leaks into another.

11 steps5 chapters~5 min at 1.25×#oop#immutability#value objects#setters
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the Java video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–6

Payoff

Steps 7–8

Java bonus

Step 9

Recap

Steps 10–11

The code: before and after

Before

class Price {
    private int amount;
    private String currency;
    Price(int amount, String currency) {
        this.amount = amount;
        this.currency = currency;
    }
    int getAmount() { return amount; }
    String getCurrency() { return currency; }
    void setAmount(int amount) { this.amount = amount; }
}

class Booking {
    private final String car;
    private Price price;
    Booking(String car, Price price) {
        this.car = car;
        this.price = price;
    }
    String line() {
        return car + ": " + price.getAmount()
                + " " + price.getCurrency();
    }
    boolean sameRateAs(Booking other) {
        return price == other.price;
    }
}

class Desk {
    public static void main(String[] args) {
        Price weekend = new Price(120, "USD");
        Booking ana = new Booking("Golf", weekend);
        Booking ben = new Booking("Polo", weekend);
        System.out.println(ana.line());
        System.out.println(ben.line());
        System.out.println(ana.sameRateAs(ben));
    }
}

After

record Price(int amount, String currency) {
    Price plus(int extra) {
        return new Price(amount + extra, currency);
    }
}

class Booking {
    private final String car;
    private Price price;
    Booking(String car, Price price) {
        this.car = car;
        this.price = price;
    }
    String line() {
        return car + ": " + price.amount()
                + " " + price.currency();
    }
    boolean sameRateAs(Booking other) {
        return price.equals(other.price);
    }
    void addExtra(int extra) {
        price = price.plus(extra);
    }
}

class Desk {
    public static void main(String[] args) {
        Price weekend = new Price(120, "USD");
        Booking ana = new Booking("Golf", weekend);
        Booking ben = new Booking("Polo", weekend);
        ana.addExtra(15);
        System.out.println(ana.line());
        System.out.println(ben.line());
        System.out.println(ana.sameRateAs(ben));
    }
}

Transcript, step by step

Problem

Step 1: One weekend rate Before

This is the same car rental desk that sent receipts last time, and today it prices bookings. A Price holds an amount and a currency, and it has a setter, a method that changes one field, here set amount. A Booking holds a car and a price, prints one line, and checks whether two bookings pay the same rate by asking if they hold the same Price object. The desk makes one weekend rate and gives it to two customers, Ana and Ben, and the run prints Golf and Polo at a hundred twenty dollars each, then true. Both bookings cost the same, so making the weekend price once and passing it to both looked like the obvious choice.

Step 2: Ana adds a child seat Code smell

Ana adds a child seat for fifteen dollars. The quick way gives Booking an add extra method that reads the amount and sets it fifteen higher. Ana's line prints a hundred thirty five, but Ben's line prints a hundred thirty five as well, and Ben never asked for a seat.

Step 3: A shared mutable price Code smell

A mutable object is one whose fields can change after it is made, and a shared reference is two variables that point at the same object. Put them together and you get a shared mutable price, so a setter called through one booking changes the price the other booking reads. You can see it in the setter call here, in Ana's booking here, and in Ben's booking, which holds the same object, here. The bug sits in neither line alone, so to find it you have to trace every place a Price is shared. The usual workaround is to copy the Price before each change, and one forgotten copy brings the bug back.

Refactor

Step 4: Refactor first Back it out

So let's take the child seat out again. We'll refactor first, so a Price can't change under anyone, and then we'll add the seat.

Step 5: No setter, final fields Remove Setting Method

The first move is Remove Setting Method, so we delete set amount, and nothing called it, so the output stays the same. Both fields become final, so the compiler stops any code that tries to assign them after the constructor. That makes Price immutable, which means its fields never change after it is made.

Step 6: Equal by value Change Reference to Value

The old double equals only said true because both bookings share one object, and two separate prices of a hundred twenty dollars would have said false. But a Price can never change now, so two prices with the same amount and currency can stand in for each other. That's a value object, a small immutable object that is equal to another when its values are equal. So the move is Change Reference to Value, and Price gets equals and hash code that compare the amount and the currency. Same rate as now calls equals, and the run still prints true. The desk still hands the same weekend price to both bookings, and now that's safe, because nobody can change it.

Payoff

Step 7: The child seat, again Payoff

Now the child seat comes back, and Price gets a plus method that returns a new Price with the extra added. Add extra stores that new Price in Ana's booking, and the desk calls it the same way as before. The run prints Golf at a hundred thirty five, Polo at a hundred twenty, and false, because the two rates now differ. The setter call is gone, Ana's booking now holds a new Price, and Ben's still holds the weekend one. The two weekend arguments, Ben's print line and the same rate as method didn't change in this step.

Step 8: Replaced, never changed Value object

A value object is never changed, only replaced. It fits here because two bookings share the weekend Price, so replacing it in Ana's booking can't reach Ben's. The booking is different, because it's an entity, an object with its own identity whose state may change. It's Ana's booking, so its price field may point somewhere new, but the Price it points at never changes.

Java bonus

Step 9: Price as a record Java bonus

Price was a whole class of final fields, a constructor, two getters and a hand written equals and hash code, all to hold two values. A Java record writes all of that from this one line, with final fields and equality by value built in. An earlier lesson used a record to cut boilerplate, and here it also removes the hand written equals, the part that's easiest to get wrong. Plus stays as it was, and line now calls amount and currency, the names a record gives its accessors.

Recap

Step 10: Where we started, where we ended Before / after

On the left, Price had a setter, so any booking that held it could change it for everyone. Same rate as compared references, which only worked because the bookings shared one object. On the right, Price is a record, and plus returns a new Price instead of changing the old one. Ana's extra replaces the price in her booking only, and same rate as compares values.

Step 11: When to reach for it Takeaways

Reach for it when a small object, like a price, a date range or an address, is passed around and shared. Skip it when the object has its own identity, like Ana's booking, because code that holds it must see its changes, and a copy would leave it looking at the old booking. You'll spot it by a setter on an object that more than one owner holds, or by defensive copies before every change. Java's Local Date works this way, so plus days returns a new date and leaves the old one alone.