LLD

Design Principles

Immutability

An object that cannot change after it is built is safe to pass around, share and keep. We build a bus seat's fare as an object that can change, watch one coupon change the price for the whole bus, and fix it with a fare that cannot change.

A passenger books a sleeper seat on a night bus from Bengaluru to Chennai. The seat costs $50, and the passenger applies a 20% coupon. The app should charge this passenger $40 and keep quoting $50 to everyone else. If the fare is an object that any code can change, one coupon can change the price for the whole bus.

Immutability means that an object cannot change after it is built.

The principle

An immutable object gets all its values when it is built and keeps them. To "change" it, we build a new object with the new values. Java's String works this way: name.toUpperCase() gives back the upper-case text and leaves name as it was.

A class is immutable when:

  • every field is private and final, and the constructor sets them all;
  • no method changes a field, so there are no setters;
  • the class is final, so a subclass cannot add state that changes;
  • no caller can change something the object holds, such as a list it was given.

The gain is that any code can hold a reference, and no other code can change what it sees. We can pass the object to any method, keep it in a map and hand it out from a getter.

The principle does not say that every object must be immutable. A booking has a passenger name record (PNR) number, and its status moves from confirmed to cancelled. It is the same booking before and after, so it stays one object that changes. An object like this, known by an identity such as its PNR, is an entity. Immutability fits values: an amount of money, a date range, a set of seats. Two values with the same contents can stand in for each other. Two bookings with the same contents cannot.

Example: a bus seat's fare

Each Trip holds one Money, the fare for any seat on that bus. The first Money has a method that changes its amount. Subtracting in place is easy and creates no new object:

public class Money {    private long dollars;     public Money(long dollars) {        this.dollars = dollars;    }     public long dollars() {        return dollars;    }     public void subtract(long amount) {        this.dollars -= amount;    }}

Trip.seatFare() returns its Money field itself. That is fine while every caller only reads it. Then the product team asks for coupons: FIRST20 takes 20% off, and the payment page must show the seat fare, the coupon and the amount to pay. A developer writes this:

public class CouponService {    public Money apply(Money fare, int percentOff) {        fare.subtract(fare.dollars() * percentOff / 100);        return fare;    }}

The payment page calls Money seatFare = trip.seatFare() and works out the $10 coupon. Then it calls Money toPay = coupons.apply(seatFare, 20). apply does not make a new amount. It subtracts $10 from the object it was given and returns that same object. So seatFare, toPay and the trip's own field are three names for one object, and all three now say $40.

Three references, one fare
One change to a shared object reaches everyone who holds it. Three references, in grey, point at one Money object: the trip's field, the payment page's seatFare and toPay. The coupon call, in amber, subtracts $10 from that object, so its amount goes from $50 to $40. Every reader of the object now sees $40. In red, the payment page shows a seat fare of $40 above a coupon of $10 and a total of $40, and the next passenger is quoted $40.One change to a shared object reaches everyone who holds it. Three references, in grey, point at one Money object: the trip's field, the payment page's seatFare and toPay. The coupon call, in amber, subtracts $10 from that object, so its amount goes from $50 to $40. Every reader of the object now sees $40. In red, the payment page shows a seat fare of $40 above a coupon of $10 and a total of $40, and the next passenger is quoted $40.
The coupon changes the one Money object that the trip, the payment page and the amount to pay all point at. One change to a shared object reaches everyone who holds it. Three references, in grey, point at one Money object: the trip's field, the payment page's seatFare and toPay. The coupon call, in amber, subtracts $10 from that object, so its amount goes from $50 to $40. Every reader of the object now sees $40. In red, the payment page shows a seat fare of $40 above a coupon of $10 and a total of $40, and the next passenger is quoted $40.

One line causes two bugs. The payment page shows a seat fare of $40, a coupon of $10 and a total of $40, which do not add up. The next passenger on the same bus is quoted $40, and after a second coupon, the third passenger is quoted $32.

We could make Trip.seatFare() return a copy. But every class that holds a Money would have to remember to copy it, and one forgotten copy brings the bug back. It is simpler to make Money impossible to change.

A fare that cannot change

A Java record is the short way to write an immutable class. Its fields are private final, it has no setters, no class can extend it, and it gets equals, hashCode and toString from its fields.

public record Money(long dollars) {    public Money {        if (dollars < 0) {            throw new IllegalArgumentException("negative amount: " + dollars);        }    }     public Money minus(Money other) {        return new Money(dollars - other.dollars);    }     public Money percent(int percent) {        return new Money(dollars * percent / 100);    }}

minus and percent return a new Money and leave the old one alone. The constructor refuses a negative amount. Nothing can change a Money after that check, so every Money stays valid. The coupon becomes:

public class CouponService {    public Money apply(Money fare, int percentOff) {        Money discount = fare.percent(percentOff);        return fare.minus(discount);    }}
A new object for the new amount
A new object for the new amount leaves the old amount as it was for everyone else. The trip's field and the payment page's seatFare still point at the Money record for $50, in orange. fare.minus(discount) creates a second Money record for $40, marked in amber as the new object, and toPay points at it. In purple, the next passenger reads the $50 record and is quoted $50. The payment page reads both records and shows $50, a coupon of $10 and $40.A new object for the new amount leaves the old amount as it was for everyone else. The trip's field and the payment page's seatFare still point at the Money record for $50, in orange. fare.minus(discount) creates a second Money record for $40, marked in amber as the new object, and toPay points at it. In purple, the next passenger reads the $50 record and is quoted $50. The payment page reads both records and shows $50, a coupon of $10 and $40.
minus returns a new Money, so the $50 fare stays $50 for everyone who holds it. A new object for the new amount leaves the old amount as it was for everyone else. The trip's field and the payment page's seatFare still point at the Money record for $50, in orange. fare.minus(discount) creates a second Money record for $40, marked in amber as the new object, and toPay points at it. In purple, the next passenger reads the $50 record and is quoted $50. The payment page reads both records and shows $50, a coupon of $10 and $40.

CouponService cannot repeat the old bug even by mistake, because Money has no method that changes it. Its field is final, so Java guarantees that every thread that gets a Money sees the amount it was built with. Many booking threads can read one Money without a lock.

When final is not enough

A final field always points at the same object, but that object can still change. A seat hold for two seats shows this:

import java.util.List; public record SeatHold(String tripId, List<String> seats, Money total) {}

The seat picker builds a hold from its own list, and the passenger then taps one more seat:

List<String> picked = new ArrayList<>(List.of("L4", "L5"));SeatHold hold = new SeatHold("BLR-MAA-2210", picked, new Money(100));picked.add("L6");

The record's seats field is final, but it points at the seat picker's own ArrayList. When the passenger taps L6, the hold lists three seats with a total for two. The fix is to copy the list in the record's constructor:

import java.util.List; public record SeatHold(String tripId, List<String> seats, Money total) {    public SeatHold {        seats = List.copyOf(seats);    }}

List.copyOf returns a list that cannot be changed, and it refuses a null seat. Now picked.add does not reach the hold, and hold.seats().add("L7") throws UnsupportedOperationException. The total needs no copy, because a Money cannot change.

final is not enough
A final field fixes which list the record points at, not what is in the list. On the left, SeatHold's final seats field and the seat picker's picked variable point at the same ArrayList. Adding L6 to picked, in amber, changes that list, so the hold lists three seats while its total is for two, in red. On the right, the constructor keeps an unmodifiable copy of [L4, L5]. The same add changes only the picker's ArrayList, and the hold keeps two seats, in purple.A final field fixes which list the record points at, not what is in the list. On the left, SeatHold's final seats field and the seat picker's picked variable point at the same ArrayList. Adding L6 to picked, in amber, changes that list, so the hold lists three seats while its total is for two, in red. On the right, the constructor keeps an unmodifiable copy of [L4, L5]. The same add changes only the picker's ArrayList, and the hold keeps two seats, in purple.
A final field still lets the list it points at change. A copy in the constructor stops that. A final field fixes which list the record points at, not what is in the list. On the left, SeatHold's final seats field and the seat picker's picked variable point at the same ArrayList. Adding L6 to picked, in amber, changes that list, so the hold lists three seats while its total is for two, in red. On the right, the constructor keeps an unmodifiable copy of [L4, L5]. The same add changes only the picker's ArrayList, and the hold keeps two seats, in purple.

When not to

Some objects exist to change. A Booking keeps its PNR and its SeatHold in final fields, but its status lives in a field that cancel() changes. Building a new booking for every status change would leave two objects for one booking, and other code could keep the old one. A large object that changes often, such as a seat map updated on every tap, would also be copied whole on each change. One mutable object owned by one class is simpler there.

In an interview

When you draw a class, say whether it is a value or an entity. Make values records, and say why: they can be shared, used as map keys and read by many threads without a lock. The Splitwise design keeps every amount in a Money record. The Flyweight page shares one style object across many cells, and that is safe only because the style cannot change.

Common mistakes:

  • Making everything immutable. A booking's status changes, and a new booking object for each change makes the design harder, not safer.
  • Trusting final on a collection. A final list field can still be changed through the list. Copy it with List.copyOf.
  • A method that changes this and returns it. The first apply looked like it returned a new amount, but it returned the same object, changed.

Summary

  • An immutable object gets its values when it is built and never changes. A "change" builds a new object.
  • In Java this takes private final fields, no setters, a final class, and a copy of any collection it is given. A record gives the first three.
  • Entities like a booking stay mutable, and the values they hold stay immutable.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.