On this page

Immutability, Value Objects & Defensive Copying

An immutable object can't change after it's built. That sounds like a restriction, and it is one, but it removes a whole category of bugs at a stroke. If a TimeRange can't change, nobody can extend your meeting by modifying a range they share with you. If a Money can't change, it's safe as a map key, safe to pass between threads, and safe to return from a getter without copying. The object's validity is checked once, in the constructor, and then holds forever.

From Nouns to Classes explains which concepts should be value objects (things defined by their attributes, like money, dates and addresses) and which should be entities (things with identity that persists through change, like a booking or an account). This page is about the mechanics of building value objects and immutable data correctly in Java, Python and TypeScript: what the language features actually guarantee, the equality and hashing contracts you must honour, and the defensive copying needed whenever mutable data crosses an object's boundary.

Every sample was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx). Java samples use a small check helper so they fail without the -ea flag.

1. The problem: aliasing

Two references to the same mutable object are called aliases. Any change through one is visible through the other. That's fine when you intend sharing, and a source of bugs when you don't, because the code that makes the change usually has no idea who else is holding a reference.

Here a booking system reuses a "9:00 to 10:00" slot object for two rooms. Extending one meeting silently extends the other.

// ---------- before: a mutable range shared by two bookings ----------
final class MutableRange {
    int startMin, endMin;
    MutableRange(int startMin, int endMin) { this.startMin = startMin; this.endMin = endMin; }
    void extend(int minutes) { endMin += minutes; }
}

record BookingBefore(String room, MutableRange slot) {}

// ---------- after: an immutable value; "changing" it makes a new one ----------
record TimeRange(int startMin, int endMin) {
    TimeRange {
        if (startMin < 0 || endMin > 24 * 60) throw new IllegalArgumentException("outside the day");
        if (endMin <= startMin) throw new IllegalArgumentException("end must be after start");
    }
    TimeRange extendBy(int minutes) { return new TimeRange(startMin, endMin + minutes); }
    boolean overlaps(TimeRange o) { return startMin < o.endMin && o.startMin < endMin; }
}

record Booking(String room, TimeRange slot) {
    Booking extendBy(int minutes) { return new Booking(room, slot.extendBy(minutes)); }
}

class AliasingDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        MutableRange nineToTen = new MutableRange(540, 600);
        BookingBefore a = new BookingBefore("A", nineToTen), b = new BookingBefore("B", nineToTen);
        a.slot().extend(30);
        check(b.slot().endMin == 630, "before: room B's meeting grew too");

        TimeRange slot = new TimeRange(540, 600);
        Booking x = new Booking("A", slot), y = new Booking("B", slot);   // sharing is now safe
        Booking longer = x.extendBy(30);
        check(longer.slot().endMin() == 630 && y.slot().endMin() == 600, "after: only A changed");
        check(x.slot().endMin() == 600, "after: the original booking value is untouched too");
        try { new TimeRange(600, 540); check(false, "invalid range"); } catch (IllegalArgumentException expected) { }
        System.out.println("shared values are safe once they can't change");
    }
}
from dataclasses import dataclass, replace


# ---------- before: a mutable range shared by two bookings ----------
class MutableRange:
    def __init__(self, start_min: int, end_min: int) -> None:
        self.start_min, self.end_min = start_min, end_min

    def extend(self, minutes: int) -> None:
        self.end_min += minutes


@dataclass
class BookingBefore:
    room: str
    slot: MutableRange


nine_to_ten = MutableRange(540, 600)
a, b = BookingBefore("A", nine_to_ten), BookingBefore("B", nine_to_ten)
a.slot.extend(30)
assert b.slot.end_min == 630                       # room B's meeting grew too


# ---------- after: an immutable value; "changing" it makes a new one ----------
@dataclass(frozen=True)
class TimeRange:
    start_min: int
    end_min: int

    def __post_init__(self) -> None:
        if self.start_min < 0 or self.end_min > 24 * 60:
            raise ValueError("outside the day")
        if self.end_min <= self.start_min:
            raise ValueError("end must be after start")

    def extend_by(self, minutes: int) -> "TimeRange":
        return replace(self, end_min=self.end_min + minutes)   # replace() re-runs __post_init__


@dataclass(frozen=True)
class Booking:
    room: str
    slot: TimeRange


slot = TimeRange(540, 600)
x, y = Booking("A", slot), Booking("B", slot)
longer = replace(x, slot=x.slot.extend_by(30))
assert longer.slot.end_min == 630 and y.slot.end_min == 600 and x.slot.end_min == 600
try:
    TimeRange(600, 540)
    raise AssertionError("invalid range accepted")
except ValueError:
    pass
print("shared values are safe once they can't change")
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: a mutable range shared by two bookings ----------
class MutableRange {
  constructor(public startMin: number, public endMin: number) {}
  extend(minutes: number): void { this.endMin += minutes; }
}
interface BookingBefore { room: string; slot: MutableRange }

const nineToTen = new MutableRange(540, 600);
const a: BookingBefore = { room: "A", slot: nineToTen };
const b: BookingBefore = { room: "B", slot: nineToTen };
a.slot.extend(30);
check(b.slot.endMin === 630, "before: room B's meeting grew too");

// ---------- after: an immutable value; "changing" it makes a new one ----------
class TimeRange {
  constructor(readonly startMin: number, readonly endMin: number) {
    if (startMin < 0 || endMin > 24 * 60) throw new RangeError("outside the day");
    if (endMin <= startMin) throw new RangeError("end must be after start");
    Object.freeze(this);
  }
  extendBy(minutes: number): TimeRange { return new TimeRange(this.startMin, this.endMin + minutes); }
}

interface Booking { readonly room: string; readonly slot: TimeRange }

const slot = new TimeRange(540, 600);
const x: Booking = { room: "A", slot };
const y: Booking = { room: "B", slot };
const longer: Booking = { ...x, slot: x.slot.extendBy(30) };
check(longer.slot.endMin === 630 && y.slot.endMin === 600 && x.slot.endMin === 600, "after: only A changed");
let rejected = false;
try { new TimeRange(600, 540); } catch { rejected = true; }
check(rejected, "invalid range rejected");
console.log("shared values are safe once they can't change");

There's a second, quieter benefit in the "after" code. The TimeRange constructor validates once. Every TimeRange in the system is guaranteed valid, so overlaps and every other method can trust its fields. With the mutable version, any method has to wonder whether some other code set endMin below startMin since the last check.

1.1 What immutability buys you

BenefitWhy
No aliasing bugsSharing a reference can't lead to surprise changes
Invariants checked onceValidate in the constructor and the object stays valid for life
Thread safety for freeImmutable objects can be shared across threads without locks, provided they're safely published (in Java, final fields give you this)
Safe hash keys and set membersThe hash can't change after insertion
No defensive copies on the way outYou can return an immutable field directly
Easier reasoningA value means the same thing everywhere it appears. Debugging doesn't involve "who changed this?"
CacheableHash codes and derived values can be computed once. Instances can be shared, like Integer.valueOf caching small values

The cost is allocation: every "change" creates a new object. For value objects with a handful of fields that's almost always negligible on modern runtimes, because short-lived objects are cheap for generational garbage collectors. For large collections changed in hot loops, it can matter. Section 7 covers that.

2. Language tools and what they really guarantee

Each language offers built-in support, and each has gaps that catch people out.

LanguageToolEnforced when?Deep or shallow?Notes
Javafinal fieldsCompile time (and the memory model)ShallowA final List can still have elements added
Javarecord (Java 16+)Compile timeShallowGenerates constructor, accessors, equals, hashCode, toString. Use a compact constructor to validate and copy
JavaList.of, Map.of, List.copyOfRuntime: mutators throwShallowAlso reject null elements
Python@dataclass(frozen=True)Runtime: assignment raises FrozenInstanceErrorShallowobject.__setattr__ bypasses it, so use only inside __post_init__
Pythontyping.NamedTupleRuntimeShallowA tuple with names. Compares equal to plain tuples with the same values, which is sometimes surprising
Pythontuple, frozenset, MappingProxyTypeRuntimeShallowMappingProxyType is a read-only view, not a copy
TypeScriptreadonly modifier, Readonly<T>, ReadonlyArray<T>Compile time onlyShallow (Readonly<T>)Erased at runtime. Any cast or plain JavaScript caller can mutate
TypeScriptas constCompile time onlyDeep (for literals)Makes literal types and readonly tuples
JavaScriptObject.freezeRuntime: writes throw in strict mode, ignored otherwiseShallowFreeze nested objects yourself for deep immutability

Two lessons come out of the table. First, almost everything is shallow. A frozen object holding a mutable list is only as immutable as the list. Second, TypeScript's readonly is a compile-time contract. It catches mistakes in your own typed code, but doesn't protect against callers that cast or don't use types. Combine it with Object.freeze when the object crosses a trust boundary.

2.1 A value object in each language

Here's a complete Money value object: validated on construction, immutable, compared by value, with arithmetic that returns new instances and refuses to mix currencies. The "before" is the familiar mistake of a mutable class with setters.

import java.util.*;

// ---------- before: mutable, compared by identity, any state allowed ----------
final class MoneyBefore {
    private long cents; private String currency;
    MoneyBefore(long cents, String currency) { this.cents = cents; this.currency = currency; }
    void setCents(long c) { cents = c; }
    long getCents() { return cents; }
}

// ---------- after: a record with validation and value semantics ----------
record Money(long cents, String currency) implements Comparable<Money> {
    Money {
        Objects.requireNonNull(currency, "currency");
        if (!currency.matches("[A-Z]{3}")) throw new IllegalArgumentException("ISO 4217 code expected: " + currency);
    }
    static Money of(long cents, String currency) { return new Money(cents, currency); }

    Money plus(Money other) { sameCurrency(other); return new Money(Math.addExact(cents, other.cents), currency); }
    Money minus(Money other) { sameCurrency(other); return new Money(Math.subtractExact(cents, other.cents), currency); }
    Money times(int factor) { return new Money(Math.multiplyExact(cents, factor), currency); }
    boolean isNegative() { return cents < 0; }

    public int compareTo(Money other) { sameCurrency(other); return Long.compare(cents, other.cents); }

    private void sameCurrency(Money other) {
        if (!currency.equals(other.currency)) throw new IllegalArgumentException(currency + " vs " + other.currency);
    }
    @Override public String toString() { return String.format("%s %d.%02d", currency, cents / 100, Math.abs(cents % 100)); }
}

class ValueObjectDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        MoneyBefore m1 = new MoneyBefore(500, "EUR"), m2 = new MoneyBefore(500, "EUR");
        check(!m1.equals(m2), "before: same amount, not equal");
        m1.setCents(-999_999);                                       // nothing stops this
        check(m1.getCents() == -999_999, "before: any state allowed");

        Money price = Money.of(1_250, "EUR");
        Money total = price.times(3).plus(Money.of(50, "EUR"));
        check(total.equals(Money.of(3_800, "EUR")), "value equality");
        check(price.equals(Money.of(1_250, "EUR")), "operations don't change the original");
        check(new HashSet<>(List.of(price, Money.of(1_250, "EUR"))).size() == 1, "safe in sets");
        check(total.compareTo(price) > 0, "ordered");
        try { price.plus(Money.of(1, "USD")); check(false, "mixed currencies"); } catch (IllegalArgumentException expected) { }
        try { Money.of(1, "euro"); check(false, "bad code"); } catch (IllegalArgumentException expected) { }
        System.out.println(total);
    }
}
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering


# ---------- before: mutable, compared by identity, any state allowed ----------
class MoneyBefore:
    def __init__(self, cents: int, currency: str) -> None:
        self.cents, self.currency = cents, currency


m1, m2 = MoneyBefore(500, "EUR"), MoneyBefore(500, "EUR")
assert m1 != m2                       # same amount, not equal
m1.cents = -999_999                   # nothing stops this


# ---------- after: a frozen dataclass with validation and value semantics ----------
@total_ordering
@dataclass(frozen=True)
class Money:
    cents: int
    currency: str

    def __post_init__(self) -> None:
        if not isinstance(self.cents, int):
            raise TypeError("cents must be an int")
        if not re.fullmatch(r"[A-Z]{3}", self.currency):
            raise ValueError(f"ISO 4217 code expected: {self.currency}")

    def _same(self, other: "Money") -> None:
        if self.currency != other.currency:
            raise ValueError(f"{self.currency} vs {other.currency}")

    def __add__(self, other: "Money") -> "Money":
        self._same(other)
        return Money(self.cents + other.cents, self.currency)

    def __mul__(self, factor: int) -> "Money":
        return Money(self.cents * factor, self.currency)

    def __lt__(self, other: "Money") -> bool:
        self._same(other)
        return self.cents < other.cents

    def __str__(self) -> str:
        return f"{self.currency} {self.cents // 100}.{abs(self.cents) % 100:02d}"


price = Money(1_250, "EUR")
total = price * 3 + Money(50, "EUR")
assert total == Money(3_800, "EUR") and price == Money(1_250, "EUR")
assert len({price, Money(1_250, "EUR")}) == 1          # hashable because frozen and eq
assert total > price
try:
    price.cents = 1                                    # type: ignore[misc]
    raise AssertionError("mutated a frozen dataclass")
except dataclasses.FrozenInstanceError:
    pass
for bad in (lambda: price + Money(1, "USD"), lambda: Money(1, "euro"), lambda: Money(1.5, "EUR")):  # type: ignore[arg-type]
    try:
        bad()
        raise AssertionError("invalid money accepted")
    except (ValueError, TypeError):
        pass
print(total)
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: mutable, compared by identity, any state allowed ----------
class MoneyBefore {
  constructor(public cents: number, public currency: string) {}
}
const m1 = new MoneyBefore(500, "EUR");
const m2 = new MoneyBefore(500, "EUR");
check(m1 !== m2, "before: same amount, different objects, and no equals");
m1.cents = -999.999; // nothing stops this, not even a fraction of a cent

// ---------- after: readonly fields, runtime freeze, explicit value equality ----------
class Money {
  private constructor(readonly cents: number, readonly currency: string) {
    Object.freeze(this);
  }
  static of(cents: number, currency: string): Money {
    if (!Number.isSafeInteger(cents)) throw new RangeError("cents must be a safe integer");
    if (!/^[A-Z]{3}$/.test(currency)) throw new RangeError(`ISO 4217 code expected: ${currency}`);
    return new Money(cents, currency);
  }
  plus(o: Money): Money { this.same(o); return Money.of(this.cents + o.cents, this.currency); }
  times(factor: number): Money { return Money.of(this.cents * factor, this.currency); }
  equals(o: Money): boolean { return this.cents === o.cents && this.currency === o.currency; }
  compareTo(o: Money): number { this.same(o); return Math.sign(this.cents - o.cents); }
  private same(o: Money): void {
    if (this.currency !== o.currency) throw new RangeError(`${this.currency} vs ${o.currency}`);
  }
  toString(): string {
    return `${this.currency} ${Math.trunc(this.cents / 100)}.${String(Math.abs(this.cents % 100)).padStart(2, "0")}`;
  }
}

const price = Money.of(1_250, "EUR");
const total = price.times(3).plus(Money.of(50, "EUR"));
check(total.equals(Money.of(3_800, "EUR")) && price.equals(Money.of(1_250, "EUR")), "value equality");
check(total.compareTo(price) > 0, "ordered");
try {
  (price as unknown as { cents: number }).cents = 1; // throws in strict mode, silently ignored in sloppy mode
} catch { /* either way, the value doesn't change */ }
check(price.cents === 1_250, "frozen at runtime, not just readonly at compile time");
for (const bad of [() => price.plus(Money.of(1, "USD")), () => Money.of(1, "euro"), () => Money.of(1.5, "EUR")]) {
  let failed = false;
  try { bad(); } catch { failed = true; }
  check(failed, "invalid money rejected");
}
console.log(total.toString());

A few details worth noticing:

  • Java uses Math.addExact and friends, so overflow throws instead of silently wrapping around to a negative balance.
  • Python's @total_ordering derives <=, > and >= from __lt__ and __eq__. The isinstance check on cents stops a float slipping in, which a type hint alone wouldn't.
  • TypeScript has no value equality. === on objects compares identity, so an explicit equals method is needed, and you have to remember to call it. Section 3 shows the consequences for Map and Set.
  • TypeScript uses a private constructor and a static factory so validation can't be bypassed, while Object.freeze backs the compile-time readonly with a runtime guarantee.

2.2 "Modifying" an immutable object

Since you can't change an immutable object, you create a modified copy. Each language has an idiom for it:

  • Java: "wither" methods that return a new instance, like slot.withEnd(630) or extendBy above. Records don't generate them, so write the ones you need. A JEP for derived record creation (with expressions) has been proposed but isn't in a released JDK as of Java 24.
  • Python: dataclasses.replace(obj, field=value) creates a copy with the given fields changed, and re-runs __post_init__, so validation still applies.
  • TypeScript: object spread, { ...booking, slot: newSlot }, for plain objects. Note that spreading a class instance gives you a plain object without its methods or prototype, so classes need explicit with methods.

When a value has many fields and callers want to change several at once, a Builder or a toBuilder() method keeps call sites readable. See Interfaces & API Design at Class Level for builder design.

3. Equality and hashing contracts

Value objects are compared by value, so you have to implement equality, and in Java and Python, hashing. Getting the contract wrong produces some of the most confusing bugs in programming: objects that are in a set but contains says they aren't.

3.1 The contract

Java's Object.equals documentation spells it out, and Python's data model has the same requirements:

  1. Reflexive: x.equals(x) is true.
  2. Symmetric: x.equals(y) if and only if y.equals(x).
  3. Transitive: if x.equals(y) and y.equals(z), then x.equals(z).
  4. Consistent: repeated calls give the same answer if nothing used in the comparison changed.
  5. Non-null: x.equals(null) is false.
  6. Hash consistency: if x.equals(y), then x.hashCode() == y.hashCode(). (The reverse isn't required: unequal objects may share a hash.)
  7. Hash stability: an object's hash mustn't change while it's in a hash-based collection.

The common ways to break it:

MistakeConsequence
Override equals but not hashCode (Java)Equal objects land in different buckets, so HashSet.contains usually returns false for an equal object
Define __eq__ without __hash__ (Python)Python sets __hash__ to None, so instances become unhashable and set() raises TypeError
Hash on mutable fields, then mutate a keyThe entry is stranded in the wrong bucket. It's still in the collection but can't be found
equals that accepts subclasses with extra fieldsBreaks symmetry: point.equals(colourPoint) but not the reverse. Bloch's Item 10 covers this. Records and final classes avoid it
Floating-point fields compared with ==0.1 + 0.2 != 0.3. Use integers (cents) or a tolerance, and never hash on a tolerance

Immutability fixes rule 7 completely, and records, frozen dataclasses and generated methods fix rules 1 to 6. That's the strongest argument for making anything you put in a set or use as a map key immutable.

import java.util.*;

// ---------- before: correct equals and hashCode, but on mutable fields ----------
final class MutablePoint {
    int x, y;
    MutablePoint(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) { return o instanceof MutablePoint p && p.x == x && p.y == y; }
    @Override public int hashCode() { return 31 * x + y; }
}

// ---------- after: a record — immutable, with equals and hashCode generated ----------
record Point(int x, int y) {
    Point moveBy(int dx, int dy) { return new Point(x + dx, y + dy); }
}

class EqualityDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        MutablePoint key = new MutablePoint(1, 2);
        Set<MutablePoint> visited = new HashSet<>(List.of(key));
        key.x = 5;                                                     // mutate a key that's in the set
        check(!visited.contains(key), "before: lost, even when looking up the very same object");
        check(!visited.contains(new MutablePoint(5, 2)), "before: and by value");
        check(visited.size() == 1 && visited.iterator().next() == key, "before: yet it's still in there");

        Set<Point> seen = new HashSet<>(List.of(new Point(1, 2)));
        check(seen.contains(new Point(1, 2)), "after: found by value");
        Point moved = new Point(1, 2).moveBy(4, 0);
        check(!seen.contains(moved) && seen.contains(new Point(1, 2)), "after: moving makes a new key");
        check(new Point(1, 2).hashCode() == new Point(1, 2).hashCode(), "equal values, equal hashes");
        System.out.println("immutable keys can't get lost");
    }
}
from dataclasses import dataclass


# ---------- before 1: __eq__ without __hash__ makes instances unhashable ----------
class PointEqOnly:
    def __init__(self, x: int, y: int) -> None:
        self.x, self.y = x, y

    def __eq__(self, other: object) -> bool:
        return isinstance(other, PointEqOnly) and (self.x, self.y) == (other.x, other.y)


assert PointEqOnly.__hash__ is None
try:
    {PointEqOnly(1, 2)}
    raise AssertionError("expected TypeError")
except TypeError:
    pass


# ---------- before 2: hashable but mutable, so keys get lost ----------
@dataclass(unsafe_hash=True)          # the name is a warning
class MutablePoint:
    x: int
    y: int


key = MutablePoint(1, 2)
visited = {key}
key.x = 5
assert key not in visited and len(visited) == 1   # stranded in the wrong slot


# ---------- after: frozen dataclass — immutable, eq and hash generated ----------
@dataclass(frozen=True)
class Point:
    x: int
    y: int

    def move_by(self, dx: int, dy: int) -> "Point":
        return Point(self.x + dx, self.y + dy)


seen = {Point(1, 2)}
assert Point(1, 2) in seen
assert Point(1, 2).move_by(4, 0) not in seen and Point(1, 2) in seen
assert hash(Point(1, 2)) == hash(Point(1, 2))
print("immutable keys can't get lost")
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: Map and Set compare object keys by identity ----------
interface PointLike { x: number; y: number }
const visited = new Set<PointLike>([{ x: 1, y: 2 }]);
check(!visited.has({ x: 1, y: 2 }), "before: an equal object is a different key");

const shared: PointLike = { x: 1, y: 2 };
const byRef = new Map<PointLike, string>([[shared, "start"]]);
shared.x = 5; // found by reference, but the key no longer means (1, 2)
check(byRef.get(shared) === "start" && byRef.get({ x: 1, y: 2 }) === undefined, "before: meaning drifted");

// ---------- after: immutable value with a canonical key for collections ----------
class Point {
  private constructor(readonly x: number, readonly y: number) { Object.freeze(this); }
  static of(x: number, y: number): Point {
    if (!Number.isInteger(x) || !Number.isInteger(y)) throw new RangeError("integer coordinates");
    return new Point(x, y);
  }
  get key(): string { return `${this.x},${this.y}`; }
  equals(o: Point): boolean { return this.x === o.x && this.y === o.y; }
  moveBy(dx: number, dy: number): Point { return Point.of(this.x + dx, this.y + dy); }
}

/** A set of points keyed by value. */
class PointSet {
  private readonly items = new Map<string, Point>();
  add(p: Point): this { this.items.set(p.key, p); return this; }
  has(p: Point): boolean { return this.items.has(p.key); }
  get size(): number { return this.items.size; }
}

const seen = new PointSet().add(Point.of(1, 2)).add(Point.of(1, 2));
check(seen.size === 1 && seen.has(Point.of(1, 2)), "after: found by value");
check(!seen.has(Point.of(1, 2).moveBy(4, 0)), "after: moving makes a new key");
console.log("immutable keys can't get lost");

Notice the Java "before" has a correct equals and hashCode. The only mistake is that the fields they use can change. That's why "make it immutable" is the real fix, not "write hashCode more carefully."

TypeScript and value equality

JavaScript has no hook for custom equality in Map, Set or ===. The two usual workarounds are a canonical string key (as above), or a small wrapper collection. A proposal for deeply immutable Records and Tuples with value equality (#{ x: 1 }) was explored by TC39 for years but was withdrawn in 2025, so don't plan around it. Libraries like Immutable.js provide value-equal collections if you need them throughout.

4. Defensive copying

Immutability within a class is easy. The hard part is the boundary, where mutable data arrives from callers or leaves through getters. A class that stores a caller's mutable list, or hands out its own, has given someone else a way to change its state without going through its methods, and its invariants are no longer its own.

The rule, from Effective Java Item 50: make defensive copies of mutable inputs when they come in, and of mutable fields when they go out.

  1. Copy in. In the constructor (and any method that stores a parameter), copy mutable arguments before storing them.
  2. Validate the copy, not the original. Check invariants after copying. Otherwise another thread can change the original between your check and your copy, a time-of-check to time-of-use race.
  3. Copy out, or return an unmodifiable value. Never return a mutable internal field. If the field is already an immutable collection, return it directly.
  4. Don't use clone() on untrusted types for copying. A subclass of the argument's type could override clone to keep a reference. Use a constructor or a static copy method of a type you trust.

Here's a team limited to five members. The "before" class stores the caller's list and returns its own, so the limit can be broken from outside in two different ways.

import java.util.*;

// ---------- before: stores the caller's list, returns its own ----------
final class TeamBefore {
    private final List<String> members;     // final reference, mutable contents
    TeamBefore(List<String> members) {
        if (members.size() > 5) throw new IllegalArgumentException("max 5 members");
        this.members = members;
    }
    List<String> members() { return members; }
}

// ---------- after: copy in, validate the copy, hand out an unmodifiable list ----------
record Team(String name, List<String> members) {
    static final int MAX = 5;
    Team {
        members = List.copyOf(members);                         // copy first (also rejects nulls)
        if (members.size() > MAX) throw new IllegalArgumentException("max " + MAX + " members");
        if (new HashSet<>(members).size() != members.size()) throw new IllegalArgumentException("duplicate member");
    }
    Team with(String member) {
        List<String> next = new ArrayList<>(members);
        next.add(member);
        return new Team(name, next);                           // the constructor re-validates
    }
}

class DefensiveCopyDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        List<String> input = new ArrayList<>(List.of("ana", "bo"));
        TeamBefore leaky = new TeamBefore(input);
        input.addAll(List.of("cy", "dee", "eli", "fay"));       // way 1: keep the reference you passed in
        check(leaky.members().size() == 6, "before: six members on a team of max five");
        leaky.members().clear();                                  // way 2: mutate what the getter returned
        check(leaky.members().isEmpty(), "before: emptied from outside");

        List<String> input2 = new ArrayList<>(List.of("ana", "bo"));
        Team team = new Team("core", input2);
        input2.add("cy");
        check(team.members().equals(List.of("ana", "bo")), "after: caller's later changes don't leak in");
        try { team.members().add("x"); check(false, "should be unmodifiable"); }
        catch (UnsupportedOperationException expected) { }
        Team bigger = team.with("cy").with("dee").with("eli");
        try { bigger.with("fay"); check(false, "limit"); } catch (IllegalArgumentException expected) { }
        try { team.with("ana"); check(false, "duplicate"); } catch (IllegalArgumentException expected) { }
        System.out.println(bigger);
    }
}
from dataclasses import dataclass


# ---------- before: frozen, but holding a mutable list ----------
@dataclass(frozen=True)
class TeamBefore:
    name: str
    members: list[str]

    def __post_init__(self) -> None:
        if len(self.members) > 5:
            raise ValueError("max 5 members")


data = ["ana", "bo"]
leaky = TeamBefore("core", data)
data += ["cy", "dee", "eli", "fay"]          # the caller kept a reference
assert len(leaky.members) == 6               # frozen is shallow
leaky.members.clear()                        # and the attribute is still a mutable list
assert leaky.members == []


# ---------- after: convert to a tuple, validate the copy ----------
@dataclass(frozen=True)
class Team:
    name: str
    members: tuple[str, ...]
    MAX = 5

    def __post_init__(self) -> None:
        copied = tuple(self.members)                    # accepts any iterable, stores an immutable copy
        object.__setattr__(self, "members", copied)     # the one sanctioned use, inside __post_init__
        if len(copied) > self.MAX:
            raise ValueError(f"max {self.MAX} members")
        if len(set(copied)) != len(copied):
            raise ValueError("duplicate member")

    def with_member(self, member: str) -> "Team":
        return Team(self.name, self.members + (member,))


data2 = ["ana", "bo"]
team = Team("core", data2)  # type: ignore[arg-type]
data2.append("cy")
assert team.members == ("ana", "bo")
assert not hasattr(team.members, "append")
bigger = team.with_member("cy").with_member("dee").with_member("eli")
for bad in (lambda: bigger.with_member("fay"), lambda: team.with_member("ana")):
    try:
        bad()
        raise AssertionError("invariant broken")
    except ValueError:
        pass
print(bigger)
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

// ---------- before: readonly reference, mutable contents, caller's array stored ----------
class TeamBefore {
  constructor(readonly name: string, readonly members: string[]) {
    if (members.length > 5) throw new RangeError("max 5 members");
  }
}
const data = ["ana", "bo"];
const leaky = new TeamBefore("core", data);
data.push("cy", "dee", "eli", "fay");
check(leaky.members.length === 6, "before: readonly doesn't stop this");
leaky.members.length = 0;
check(leaky.members.length === 0, "before: emptied from outside");

// ---------- after: copy in, freeze, expose a ReadonlyArray ----------
class Team {
  static readonly MAX = 5;
  readonly members: readonly string[];
  constructor(readonly name: string, members: Iterable<string>) {
    const copy = Object.freeze([...members]);
    if (copy.length > Team.MAX) throw new RangeError(`max ${Team.MAX} members`);
    if (new Set(copy).size !== copy.length) throw new RangeError("duplicate member");
    this.members = copy;
    Object.freeze(this);
  }
  with(member: string): Team { return new Team(this.name, [...this.members, member]); }
}

const data2 = ["ana", "bo"];
const team = new Team("core", data2);
data2.push("cy");
check(team.members.join() === "ana,bo", "after: caller's changes don't leak in");
let blocked = false;
try { (team.members as string[]).push("x"); } catch { blocked = true; }
check(blocked, "after: frozen at runtime even if someone casts");
const bigger = team.with("cy").with("dee").with("eli");
for (const bad of [() => bigger.with("fay"), () => team.with("ana")]) {
  let failed = false;
  try { bad(); } catch { failed = true; }
  check(failed, "invariants hold");
}
console.log(bigger.members);

The Python "before" is worth a second look. frozen=True gives a false sense of safety: you can't reassign members, but you can mutate the list it points to. The same is true of a Java record with a List component, and of a TypeScript readonly array field. All three are shallow.

4.1 Where copies are needed

SituationCopy?
Constructor or setter receives a mutable collection, array or dateYes, copy in
Getter returns a mutable fieldYes, copy out, or store an unmodifiable collection and return that
Field is an immutable type (String, Instant, LocalDate, record of immutables)No
Field is an immutable collection of mutable elementsThe collection is safe. The elements aren't, so make them immutable too
Internal, private helper passing data within the classNo. The boundary is the class's public surface
Performance-critical path where the caller is trusted and documentedPossibly not, but document the ownership transfer ("the caller must not modify the array after passing it")

Java's old java.util.Date is mutable, which is why pre-Java 8 code is full of new Date(d.getTime()) copies. The java.time types (Instant, LocalDate, Duration) are immutable, so modern code doesn't need those copies at all. That's the general lesson: the best defensive copy is a field type that doesn't need one.

5. Immutable collections: views versus copies

Each language offers two different things that both get called "immutable collections," and confusing them causes bugs.

  • An unmodifiable view wraps an existing collection and rejects writes through the view. But if the original changes, the view shows the change. Java's Collections.unmodifiableList, Python's types.MappingProxyType and a TypeScript ReadonlyArray type on an existing array are all views.
  • An immutable copy is a separate collection that nothing can change. Java's List.copyOf and List.of, Python's tuple and frozenset, and a frozen spread copy in TypeScript are copies.
import java.util.*;

class ViewVersusCopyDemo {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        List<String> backing = new ArrayList<>(List.of("a", "b"));
        List<String> view = Collections.unmodifiableList(backing);
        List<String> copy = List.copyOf(backing);

        backing.add("c");
        check(view.equals(List.of("a", "b", "c")), "the view shows the change");
        check(copy.equals(List.of("a", "b")), "the copy doesn't");

        try { view.add("x"); check(false, "view is read-only"); } catch (UnsupportedOperationException expected) { }
        try { copy.add("x"); check(false, "copy is read-only"); } catch (UnsupportedOperationException expected) { }

        check(List.copyOf(copy) == copy, "copying an immutable list returns the same instance: no cost");
        try { List.of("a", null); check(false, "nulls"); } catch (NullPointerException expected) { }
        System.out.println("view " + view + ", copy " + copy);
    }
}
from types import MappingProxyType

backing = {"a": 1}
view = MappingProxyType(backing)     # read-only view
copy = dict(backing)                 # independent copy (a plain dict: mutable, but not shared)
frozen = frozenset(backing.items())  # independent and immutable

backing["b"] = 2
assert dict(view) == {"a": 1, "b": 2}           # the view shows the change
assert copy == {"a": 1} and frozen == frozenset({("a", 1)})

try:
    view["c"] = 3                                # type: ignore[index]
    raise AssertionError("view should be read-only")
except TypeError:
    pass

items = ["a", "b"]
as_tuple = tuple(items)
items.append("c")
assert as_tuple == ("a", "b")
assert tuple(as_tuple) is as_tuple               # copying a tuple is free
print("view", dict(view), "copy", copy)
function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(what);
}

const backing: string[] = ["a", "b"];
const view: readonly string[] = backing;              // a readonly *type*, same array
const copy: readonly string[] = Object.freeze([...backing]);

backing.push("c");
check(view.join() === "a,b,c", "the view shows the change");
check(copy.join() === "a,b", "the copy doesn't");

// view.push("x")  -> compile error, but only a compile error:
(view as string[]).push("x");
check(backing.length === 4, "a cast mutates the original through the 'readonly' view");

let blocked = false;
try { (copy as string[]).push("x"); } catch { blocked = true; }
check(blocked, "the frozen copy refuses at runtime");
console.log("view", view, "copy", copy);

Views are useful when you deliberately want callers to see live data without being able to modify it, like a read-only window onto a cache. They're the wrong tool for protecting an invariant, because the owner of the backing collection can still change it. For invariants, use copies.

5.1 Persistent data structures

Copying a 10,000-element list to add one item is wasteful. Persistent data structures solve this with structural sharing: a "modified" version shares most of its internal nodes with the original, so adding an element costs O(log n) rather than O(n), and both versions remain valid. Clojure and Scala's collections work this way, as do libraries like Immutable.js for JavaScript, pyrsistent for Python and Vavr or PCollections for Java.

In LLD interviews you'll rarely need them, but knowing they exist answers the follow-up "isn't immutability slow for large collections?"

6. Immutability and thread safety

Immutable objects are the easiest thread-safe objects to write, because there's nothing to synchronise: no thread can observe a half-finished update if no updates happen. But "immutable" has to be true in the right sense for that to hold.

  • The state must be fully set in the constructor and never change afterwards. That includes everything reachable from the object. A record holding a mutable ArrayList isn't thread-safe just because it's a record.
  • The object must be safely published. In Java, the memory model guarantees that once a constructor finishes, any thread that sees a reference to the object also sees the correct values of its final fields, without locks (JLS §17.5). That guarantee is why immutable Java classes should use final fields, and it doesn't hold for non-final fields set in the constructor. Records' fields are final, so records get this for free.
  • this must not escape during construction. If a constructor registers this as a listener, or starts a thread that uses it, another thread can see the object before its fields are set, and the final-field guarantee no longer applies.

Python's GIL and JavaScript's single-threaded event loop make the memory-model details less pressing, but the design point carries over to async code: an immutable value passed into an awaited call can't change while you're suspended, whereas a mutable one can be changed by another task in the meantime.

6.1 The immutable snapshot pattern

A common way to use immutability in a concurrent design is to keep mutable state as a single reference to an immutable snapshot. Readers grab the current snapshot and use it without locks. A writer builds a new snapshot and swaps the reference atomically.

  1. Configuration, a routing table or a price list is held in an immutable object.
  2. Readers call current() and get a snapshot that can't change under them, however long they hold it.
  3. An update builds a new snapshot, from a copy of the old one plus the change, and replaces the reference: AtomicReference.set in Java, or a compare-and-set loop if updates can race.

Java's CopyOnWriteArrayList is this idea applied to a list, and it suits read-heavy, rarely written data such as listener lists. The pattern turns a hard problem (many threads reading and writing shared mutable state) into an easy one (many threads reading immutable data, plus one atomic swap). It's covered with locking alternatives in Classic Synchronization Problems.

6.2 Common mistakes

  • Leaving a field non-final "because it's never changed." It may never be changed, but without final Java doesn't give you the safe-publication guarantee, and the next maintainer can't tell it's meant to be constant.
  • Lazy initialisation without thought. A cached hash code computed on first use is fine if it's idempotent (every thread computes the same value), which is how String does it. A lazily created collaborator is mutation and needs proper synchronisation.
  • Exposing a builder as the value. Returning the mutable builder rather than calling build() hands callers an object they can still change.
  • Freezing the wrapper, not the contents. Object.freeze(order) where order.lines is an array leaves the lines mutable. Freeze or copy each level that matters.

7. Where mutability is the right call

Immutability is the default for values, not a universal law.

  • Entities change by definition. A Booking moves from held to confirmed to cancelled. Model that with controlled mutation through methods that enforce transitions (booking.confirm()), not by making the entity immutable and replacing it everywhere. Its fields can still be immutable values: the TimeRange, the Money and the SeatId inside it.
  • Builders and accumulators. StringBuilder, a list being filled in a loop, or a Builder are mutable on purpose, and short-lived. The rule is to keep the mutable phase local and hand out an immutable result.
  • Hot paths with large data. A simulation updating a million particles per frame, a game board, or a matrix computation. Mutation in place, confined to one owner, is fine. Document it and don't share the mutable object.
  • Caches and lazily computed fields inside an otherwise immutable object, like String caching its hash code. That's invisible mutation and is fine if it's thread-safe and idempotent.

A good rule of thumb: make it immutable unless it has identity and a lifecycle, or unless measurement shows the copying costs too much. And when something is mutable, confine it. One owner, no aliases escaping.

8. When it goes too far

Over-applicationSymptomBetter
Immutable entitiesbooking = booking.withStatus(CONFIRMED) everywhere, and stale copies held by other objects show the old statusEntities mutate through methods. Values are immutable
Deep-copying everythingCopying collections of immutable elements, or copying in private helpersCopy only at the public boundary, and only mutable things
Freezing everything at runtimeObject.freeze deep-walks on every object in a hot pathUse readonly types internally, and freeze at trust boundaries
Value objects for everythingFirstName, LastName, MiddleInitial wrappers with no rulesWrap when there's validation, behaviour or a real risk of mixing values up
Wither chainsp.withA(1).withB(2).withC(3).withD(4) creating four objectsA builder or a single factory taking the changes
Rejecting mutable buildersBuilding a 50-element list by repeated immutable appends, O(n²)Build mutably and locally, then freeze once

9. How it shows up in LLD interviews

Immutability is one of the cheapest ways to show design maturity in an LLD round, because it's mostly a matter of habit.

Where it matters:

  • Money, time ranges, coordinates, seat ids, addresses. Make them immutable value objects in the class diagram (stereotype them <<value>> if you like). See Primitive obsession for why they should exist at all.
  • Map keys and set members. Booked seats in a Set<SeatId>, a board keyed by Position. If the key type is mutable, an interviewer may ask what happens if it changes.
  • Getters on aggregates. ParkingLot.getSpots() returning the internal list lets callers bypass allocation rules. Return an unmodifiable copy, or better, don't expose the list at all and offer the query callers actually need.
  • Concurrency follow-ups. "Is this thread-safe?" is much easier to answer when most objects are immutable. Only the mutable entities need locking. See Classic Synchronization Problems for the locking side.
  • Events and commands. SeatBooked, PaymentFailed and other events should be immutable. They describe something that already happened.

What to say:

  • "Money and TimeRange are immutable records. They validate in the constructor, so every instance is valid."
  • "I copy the list in the constructor and return an unmodifiable view of my own copy, so callers can't break the five-member limit."
  • "Seat ids are immutable, so they're safe as keys in the booked-seats set."
  • "The booking is an entity, so it's mutable, but only through confirm and cancel. Its fields are immutable values."

Red flags:

  • Setters on value objects (money.setAmount).
  • double for money.
  • Returning internal mutable collections.
  • equals without hashCode in Java.
  • Using a mutable object as a map key.

10. Interview questions

  1. "What are the benefits of immutability?" No aliasing bugs, invariants checked once in the constructor, thread safety without locks, safe use as hash keys, no need for defensive copies on the way out, and simpler reasoning. The main cost is allocating new objects for changes, which is usually negligible for small values.

  2. "Is a Java record immutable?" Shallowly. Its fields are final and it has no setters, but a record with a List component holds whatever list it was given, which may be mutable. Copy in the compact constructor with List.copyOf to make it deeply immutable for that field.

  3. "What's the contract between equals and hashCode?" Equal objects must have equal hash codes, and an object's hash must not change while it's in a hash-based collection. equals must be reflexive, symmetric, transitive, consistent and false for null. Breaking the hash rules makes objects unfindable in HashSet and HashMap.

  4. "What happens if you mutate a key in a HashMap?" Its hash changes, so lookups go to a different bucket and fail, even when using the same object. The entry is still in the map, still counted in size() and visible when iterating, but is effectively lost. The fix is to use immutable keys.

  5. "Why does Python make my class unhashable when I define __eq__?" Because a default identity-based hash would be inconsistent with your value-based equality. Python sets __hash__ = None to stop you breaking the contract. Use @dataclass(frozen=True) to get a consistent __eq__ and __hash__, or define __hash__ yourself over immutable fields.

  6. "What is defensive copying, and where do you do it?" Copying mutable data at an object's boundary so outside code can't change its state behind its back. Copy mutable inputs in constructors and setters, validate the copy rather than the original, and return copies or unmodifiable collections from getters. Immutable field types make most copies unnecessary.

  7. "What's the difference between Collections.unmodifiableList and List.copyOf?" The first is a read-only view: changes to the backing list show through it. The second is an independent immutable copy. Use copies to protect invariants. List.copyOf also returns the same instance if given an already immutable list, and rejects nulls.

  8. "Does TypeScript's readonly make an object immutable?" Only at compile time. It's erased in the emitted JavaScript, so a cast or untyped caller can still mutate it. For runtime protection use Object.freeze, which is shallow, so freeze nested objects too where it matters.

  9. "Should entities be immutable?" Usually not. Entities have identity and a lifecycle, so they change through methods that enforce valid transitions. Their attributes should be immutable value objects. Some designs, especially event-sourced ones, do treat entity state as an immutable snapshot rebuilt from events, but that's a deliberate architectural choice.

  10. "Isn't immutability slow?" For small value objects, rarely, because short-lived allocations are cheap for generational GCs and immutability removes copying elsewhere. For large collections, use persistent data structures with structural sharing, or build mutably in a confined scope and freeze once. Measure before trading safety for speed.