The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·34

Object-Oriented Programming and Its Alternatives

The four pillars (encapsulation, abstraction, inheritance, polymorphism), the relationships between objects (composition, aggregation, association, dependency), substitutability, composition over inheritance, immutability, identity and value objects. OOP is compared with how Go, Rust, Zig, C, functional languages, data-oriented design and actors solve the same problems.

31 topics · ~38 min read · 28-question quiz
Updated Suggest a correction

Start here: objects, and when not to use them

What problem objects solve

As programs grow, the hard part isn't writing code but keeping data and the rules about that data together, so that no part of a large codebase can put the data into a nonsensical state. An order shouldn't be changeable after payment; its total must always equal the sum of its items. Object-oriented programming (OOP) bundles data with the only operations allowed to change it, into objects made from classes. Java, C#, Kotlin, C++ and Python are built around it; Go, Rust and functional languages take different routes to the same goals (the full-depth sections compare them).

Encapsulation: guard the rules

Java
final class Order {
    private final List<String> items = new ArrayList<>();
    private int totalPaise;
    private boolean paid;

    void add(String item, int pricePaise) {
        if (paid) throw new IllegalStateException("can't change a paid order");
        if (pricePaise <= 0) throw new IllegalArgumentException("bad price");
        items.add(item); totalPaise += pricePaise;
    }
    void markPaid() { if (items.isEmpty()) throw new IllegalStateException("empty order"); paid = true; }
    int total() { return totalPaise; }
    List<String> items() { return List.copyOf(items); }      // hand out a read-only copy, not our list
}
Text
blocked: can't change a paid order
blocked: can't modify the items list from outside
total ₹120, items [Masala dosa, Filter coffee]

The fields are private, so the only way to change an order is through methods that enforce the rules. The rules that must always hold (the total matches the items; paid orders don't change) are the class's invariants. Notice the subtle part: returning the internal items list directly would let any caller add a free dessert behind the order's back; returning a copy keeps the invariant safe. Contrast this with a class of public fields and setters for everything, which looks object-oriented but enforces nothing (an "anaemic" model).

Polymorphism: one interface, many forms

Code often needs to treat different things the same way: UPI, card and cash are all ways to pay. Define the capability as an interface and let each kind implement it:

Java
interface PaymentMethod { String pay(int paise); }
record Upi(String vpa) implements PaymentMethod { public String pay(int p) { return "UPI collect ₹" + p / 100 + " from " + vpa; } }
record Card(String last4) implements PaymentMethod { public String pay(int p) { return "charge ₹" + p / 100 + " to card …" + last4; } }
record Cash() implements PaymentMethod { public String pay(int p) { return "collect ₹" + p / 100 + " at the counter"; } }

for (PaymentMethod m : List.of(new Upi("asha@okbank"), new Card("4242"), new Cash())) System.out.println(m.pay(order.total()));
Text
UPI collect ₹120 from asha@okbank
charge ₹120 to card …4242
collect ₹120 at the counter

The loop doesn't know or care which kind each element is: the JVM calls the right pay at run time (dynamic dispatch). Adding a new payment method (wallets, net banking) means adding one class, without touching the loop or any code that uses PaymentMethod. That's polymorphism's payoff: code that's open for extension but doesn't need editing.

The other way: data plus pattern matching

Functional languages, Rust's enums and modern Java's sealed interfaces offer a second design: a closed set of data types, and functions that switch over them:

Java
sealed interface Payment permits UpiP, CardP, CashP {}
record UpiP(String vpa) implements Payment {}
record CardP(String last4) implements Payment {}
record CashP() implements Payment {}

static String describe(Payment p) {
    return switch (p) {                                     // the compiler checks every case is handled
        case UpiP u -> "UPI " + u.vpa();
        case CardP c -> "card …" + c.last4();
        case CashP c -> "cash";
    };
}

The trade-off is the expression problem (full-depth section): with interfaces it's easy to add new kinds (a new class) but every new operation means editing every class; with sealed types and switches it's easy to add new operations (a new function) but adding a kind means updating every switch, which the compiler conveniently lists for you. Use interfaces for open, pluggable sets (payment providers, storage backends) and sealed types for closed sets of domain cases (order states, events, results).

Inheritance, and why composition usually wins

A class can extend another, inheriting its fields and methods. It's tempting for reuse, and it's the most commonly misused feature in OOP: a subclass depends on the internal details of its parent, so a change in the parent can break it, and a subclass can't always honour its parent's promises. The lab shows both failures in a few lines: a counting subclass of HashSet that counts every item twice, and a Square that breaks code written for Rectangle. The usual advice, favour composition over inheritance, means holding another object as a field and delegating to it, instead of extending it. Reserve inheritance for genuine "is-a" relationships designed for extension (abstract base classes in a framework, sealed hierarchies).

Values versus entities

Some objects are defined by their identity: order #4512 is still the same order after its status changes. Others are defined only by their value: ₹90 is ₹90, and two Money(9000, "INR") objects are interchangeable. Model values as small immutable types (records are ideal) with value-based equals, and keep identity-bearing entities (orders, customers) as classes with an id. Immutable values can be shared freely, used safely as map keys and across threads, and never change behind your back.

How deep to go in OOP and its alternatives

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain encapsulation, abstraction, inheritance, polymorphism, composition
L2 Design classes with invariants, interfaces for capabilities, records for values
L3 Explain dispatch, the expression problem, Liskov substitution, value vs identity, and how Go, Rust and functional languages achieve the same goals
L4 Diagnose fragile base classes, broken equals/hashCode, leaked mutable state and substitutability bugs
L5 Choose between OOP, sealed types and functional designs per part of a domain model
L6 Set modelling conventions for a large codebase and evolve them without breaking clients

What OOP is for

The problem objects solve

Large programs fail because everything can touch everything. A global variable modified from 40 places, or a struct whose invariants (a balance never negative, a start date before an end date) are enforced nowhere, makes every change risky. Object-oriented programming (Simula 1967, Smalltalk 1972, C++ 1985, Java 1995) answers by bundling data with the only code allowed to change it, and by letting code depend on abstract contracts instead of concrete implementations.

Alan Kay, who coined the term, emphasised messaging (objects as little computers sending messages, which Erlang's processes embody more faithfully than Java does). Mainstream OOP (C++, Java, C#) emphasises classes, inheritance and static types. Keep both views in mind: the useful core of OOP is encapsulation and polymorphism. Inheritance is the most overused part.

Other paradigms, briefly

Paradigm Unit of organisation State Polymorphism through Languages
Object-oriented Classes and objects Encapsulated, often mutable Subtyping (virtual dispatch) Java, C#, C++, Kotlin, Python, Ruby, Smalltalk
Procedural Functions + structs Exposed structs, passed explicitly Function pointers, switch on tags C, Zig (largely), Go (largely), Pascal
Functional Functions and algebraic data types Immutable values; effects pushed to edges Parametric polymorphism, type classes, pattern matching Haskell, OCaml, F#, Elixir, Clojure, Scala, Elm
Trait/protocol-oriented Data types + separately implemented behaviours Explicit ownership Traits (static or dynamic dispatch) Rust, Swift, Haskell (type classes)
Data-oriented Arrays of plain data, processed in bulk Struct-of-arrays, cache-friendly Data layout, not dispatch C, C++, Zig, Rust, Jai; game engines (ECS)
Actor model Isolated processes exchanging messages Private per actor Messages handled by pattern Erlang, Elixir, Akka/Pekko (Scala/Java), Orleans (C#)

Modern languages are multi-paradigm. Java has had lambdas, streams, records, sealed types and pattern matching since Java 8–21, so idiomatic modern Java is "OOP at the boundaries, functional and data-oriented inside". Go is procedural with interfaces. Rust is trait-based with strong functional influences. Kotlin and Scala blend OOP and FP deliberately.

The four pillars

Encapsulation

Encapsulation means hiding an object's internal representation behind an interface, so that invariants can be enforced in one place and the representation can change without breaking callers.

Interactive diagram: Dynamic dispatch: one call, the right method. It needs JavaScript; the text around it says the same.

It's not "make fields private and add getters and setters". A class with private fields and public setters for each is a struct with extra steps. Encapsulation is about behaviour-rich operations that preserve invariants:

// Anaemic: no invariant is protected. Any caller can set end before start.
public class Booking {
    private LocalDate start, end;
    public void setStart(LocalDate s) { start = s; }
    public void setEnd(LocalDate e) { end = e; }
}

// Encapsulated: the only ways to change state preserve "start <= end" and "not cancelled"
public final class Booking {
    private LocalDate start, end;
    private boolean cancelled;

    public Booking(LocalDate start, LocalDate end) { reschedule(start, end); }

    public void reschedule(LocalDate newStart, LocalDate newEnd) {
        if (cancelled) throw new IllegalStateException("cancelled bookings can't move");
        if (newEnd.isBefore(newStart)) throw new IllegalArgumentException("end before start");
        this.start = newStart; this.end = newEnd;
    }
    public void cancel() { cancelled = true; }
    public long nights() { return ChronoUnit.DAYS.between(start, end); }  // derived, not stored
}

Tell, don't ask: rather than if (account.getBalance() >= amt) account.setBalance(account.getBalance() - amt) in the caller (the check and update are separated, and racy), write account.withdraw(amt) and let the object enforce the rule. The Law of Demeter ("talk only to your immediate friends") warns against order.getCustomer().getAddress().getCity() chains, which couple the caller to the whole object graph.

Abstraction

Abstraction means exposing what something does and hiding how. Encapsulation hides data; abstraction hides decisions. An OrderRepository interface abstracts away whether orders live in Postgres, DynamoDB or memory. A Clock abstraction lets tests control time.

Good abstractions are narrow (few operations), deep (lots of functionality behind a simple interface, as described in John Ousterhout's A Philosophy of Software Design), and stable (they change less often than their implementations). Bad ones are leaky: they force callers to know implementation details anyway, like an ORM that requires you to understand lazy loading to avoid N+1 queries (chapter 49), or a "database-agnostic" layer that breaks on vendor-specific locking.

Every language expresses abstraction with its interface mechanism (chapter 33): Java/C# interfaces and abstract classes, Go interfaces, Rust traits, C++ abstract classes or concepts, C function-pointer tables, Haskell type classes, and module signatures in OCaml and ML.

Inheritance

Inheritance lets a subclass reuse and extend a superclass's fields and methods. It mixes two different things:

  1. Interface inheritance (subtyping): "a Circle is a Shape and can be used wherever a Shape is expected". This is the valuable part.
  2. Implementation inheritance: "Circle reuses Shape's code". This is where the trouble lives.

Problems with implementation inheritance:

  • Fragile base class: changing a superclass method can break subclasses that depend on its internal call patterns. The canonical example is the "instrumented HashSet" from Effective Java: overriding addAll and add to count insertions double-counts, because HashSet.addAll internally calls add. The subclass depends on an undocumented implementation detail.
  • Tight coupling: the subclass sees protected internals, so the superclass can never change them.
  • Rigid hierarchies: real domains rarely fit a single tree. Is a Penguin a Bird if Bird has fly()?
  • Multiple inheritance of implementation creates the diamond problem: if B and C both extend A and override foo(), which does D extends B, C get?

How languages respond:

Language Implementation inheritance Multiple inheritance
Java Single class inheritance (extends) Multiple interfaces, including default methods. If two defaults conflict, the class must override and choose (B.super.foo())
C# Single class Multiple interfaces with default implementations
Kotlin Classes are final by default (open to allow inheritance) Interfaces with defaults; delegation with by
C++ Yes, multiple, plus virtual inheritance to share one diamond base Full, which is powerful and complex
Python Multiple inheritance with the C3 linearisation method resolution order (MRO) Mixins are common
Scala Single class + multiple traits with linearisation Stackable traits
Go None. Struct embedding promotes methods, but there's no subtyping between structs —
Rust None. Traits can have default methods and supertraits (trait B: A), but structs never inherit fields —
Zig, C None —
JavaScript Prototypal: objects delegate to a prototype chain (class is sugar over it) Mixins via object composition
// Template method: the one place implementation inheritance shines (but consider a strategy instead)
public abstract class ReportJob {
    public final void run() {                  // final: the algorithm skeleton can't be overridden
        var data = load();
        var report = render(data);
        publish(report);
    }
    protected abstract List<Row> load();       // hooks subclasses fill in
    protected abstract String render(List<Row> rows);
    protected void publish(String report) { /* default: S3 */ }
}

// Design for inheritance or prohibit it (Effective Java, item 19): make classes final unless documented for extension.

Polymorphism

Polymorphism ("many forms") means one piece of code works with values of different types. There are three distinct kinds, and every language supports a different mix:

Kind Meaning Examples
Subtype (inclusion) polymorphism Code written for a supertype works for every subtype; the method called is chosen at run time by the object's actual class (dynamic dispatch) Java/C# virtual methods, C++ virtual, Go interface values, Rust dyn Trait
Parametric polymorphism (generics) Code is written once for any type T (chapter 36) Java/C#/Kotlin generics, Rust generics, C++ templates, Go type parameters, Haskell type variables, Zig comptime T: type
Ad hoc polymorphism Same name, different implementations per type, chosen by the compiler Method overloading (Java, C++, C#), operator overloading, type classes / traits (impl Add for Money)

Plus coercion polymorphism (implicit conversions such as int to double) and row/structural polymorphism (TypeScript, OCaml objects: "anything with a name: string field").

How dynamic dispatch works mechanically (Vol. 1 ch. 3 covers vtables in depth):

Shape s = … Circle objklass ptr · r Circle vtable[0] toString[1] area → Circle.area() Square objklass ptr · side Square vtable[0] toString[1] area → Square.area() s.area(): load klass from object → load slot [1] → indirect call. The JIT often inlines it.
Virtual dispatch. Each object points to its class metadata; the method table maps a slot to the implementation for that class. A call site loads the slot and jumps.
  • Java/C#: all non-static, non-private, non-final instance methods are virtual. The JVM uses class hierarchy analysis and inline caches: if only one implementation has ever been seen at a call site (monomorphic), it inlines the call behind a cheap type check, and deoptimises if a new class appears later (chapter 40). Virtual calls are therefore usually free in hot Java code.
  • C++: methods are non-virtual by default. Only virtual methods pay for dispatch. final lets the compiler devirtualise.
  • Rust: static dispatch by default (generics are monomorphised: one compiled copy per concrete type). dyn Trait opts into a vtable, stored in a fat pointer (data pointer + vtable pointer) rather than inside the object. That's why Rust structs have no header.
  • Go: interface values are (itab pointer, data pointer) pairs. Calls through interfaces are dynamic. Concrete method calls are static.
  • Zig/C: dispatch is explicit through function-pointer tables or switch on a tag.

Dispatch beyond single receivers

Java, C++, C#, Go and Rust use single dispatch: the method is chosen by the run-time type of one object (the receiver), while overloads are chosen at compile time by the static types of the arguments. That surprises people:

Java
class Printer {
    void print(Object o) { System.out.println("object"); }
    void print(String s) { System.out.println("string"); }
}
Object x = "hello";
new Printer().print(x);   // prints "object": overloads are resolved by the STATIC type (Object)

Multiple dispatch picks the implementation from the run-time types of all arguments: Common Lisp (CLOS), Julia, Clojure multimethods, and C# with dynamic. Without it, OOP languages use the visitor pattern (double dispatch) to choose behaviour per pair of types, which modern Java largely replaces with pattern-matching switch over sealed types (chapter 39).

The expression problem

Philip Wadler's expression problem names the trade-off between paradigms: can you add new types and new operations without modifying existing code and without losing type safety?

Add a new type (a Triangle shape) Add a new operation (perimeter)
OOP (class hierarchy with virtual methods) Easy: write a new subclass Hard: edit every class (or use visitors)
FP / sum types (enum + match) Hard: edit every match Easy: write a new function with a match
// OOP style: operations live in the types
interface Shape { double area(); }                       // adding perimeter() touches every implementation
record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }
record Square(double s) implements Shape { public double area() { return s * s; } }

// Data-oriented / FP style (modern Java): a sealed type + switch functions
sealed interface Shape2 permits Circle2, Square2 {}
record Circle2(double r) implements Shape2 {}
record Square2(double s) implements Shape2 {}

static double perimeter(Shape2 s) {                       // new operation: one new function
    return switch (s) {                                   // exhaustive: adding Triangle2 breaks compilation here
        case Circle2 c -> 2 * Math.PI * c.r();
        case Square2 q -> 4 * q.s();
    };
}

Rule of thumb: when the set of variants is fixed (payment methods, AST nodes, order states), use sum types and pattern matching. When third parties add variants (plugins, drivers, strategies), use interfaces and polymorphism.

Relationships between objects

Association, aggregation, composition, dependency

UML names four relationships, from weakest to strongest:

Relationship Meaning Lifetime Example UML arrow
Dependency A uses B temporarily (a parameter, a local variable, a static call) No ownership OrderService.place(Order o, Clock clock) dashed arrow
Association A knows B (holds a reference) Independent Order → Customer (customer exists without the order) solid line
Aggregation A has B, as a whole/part, but parts can exist independently and be shared Parts outlive the whole Team has Players (a player can move teams) hollow diamond
Composition A owns B: parts are created and destroyed with the whole, and not shared Parts die with the whole Order owns OrderLines filled diamond
OrderService Clockdependency: uses Order Customerassociation: knows Team Playeraggregation: has, shared Order OrderLinecomposition: owns lifetime
UML relationship notation, weakest to strongest. Composition implies ownership of the part's lifetime.

The distinction matters in practice:

  • Persistence: composition maps to cascading saves and deletes and orphan removal (@OneToMany(cascade = ALL, orphanRemoval = true), chapter 49). Association and aggregation must not cascade deletes. In DDD terms (Vol. 13), a composition boundary is often an aggregate.
  • Ownership languages make it explicit. In Rust, composition is a field holding a value (Vec<OrderLine>). Aggregation or association needs a reference type: borrowed &Player with lifetimes, shared Rc<Player>/Arc<Player>, or more often an ID (player_id: PlayerId). C++ expresses the same with values, std::unique_ptr (owns), std::shared_ptr (shared) and raw pointers or references (non-owning). Zig and C document ownership by convention (who calls deinit/free).
  • GC languages blur it: in Java, everything is a reference, so composition versus aggregation is a design intent documented by code structure (who creates and exposes the part), not something the language enforces.
  • Dependencies are what DI manages (chapter 46). Passing collaborators in through the constructor makes dependencies explicit and swappable in tests.

Composition over inheritance

The Gang of Four's advice (Design Patterns, 1994): favour object composition over class inheritance. Build behaviour by holding collaborators and delegating to them, rather than inheriting from base classes.

// Inheritance for reuse: brittle (the Effective Java instrumented-set problem)
class CountingSet<E> extends HashSet<E> {
    int added;
    @Override public boolean add(E e) { added++; return super.add(e); }
    @Override public boolean addAll(Collection<? extends E> c) { added += c.size(); return super.addAll(c); }
}
// new CountingSet<>().addAll(List.of(1, 2, 3)) → added == 6: HashSet.addAll calls add() internally

// Composition + forwarding: depends only on the Set interface contract
final class CountingSet2<E> implements Set<E> {
    private final Set<E> inner;                         // the composed collaborator
    private int added;
    CountingSet2(Set<E> inner) { this.inner = inner; }
    public boolean add(E e) { added++; return inner.add(e); }
    public boolean addAll(Collection<? extends E> c) { added += c.size(); return inner.addAll(c); }
    // … forward the other Set methods to inner (or extend a ForwardingSet helper, as in Guava)
    public int size() { return inner.size(); }
    // …
}

Composition gives you:

  • Runtime flexibility: swap collaborators (strategies) without new subclasses.
  • Narrower coupling: depend on the collaborator's public interface only.
  • Testability: inject fakes.
  • Decorators: wrap behaviour (caching, metrics, retries) around an interface without touching implementations. Spring's AOP proxies are generated decorators (chapter 46).

Inheritance is still right for true is-a relationships with a stable, documented contract designed for extension: framework base classes such as AbstractRoutingDataSource or OncePerRequestFilter, sealed hierarchies of variants, and exception hierarchies.

Subtype substitutability (Liskov)

The Liskov Substitution Principle (Barbara Liskov, 1987): if S is a subtype of T, then code written against T must work correctly with any S, without knowing which. Subtypes must honour the supertype's contract, not just its method signatures:

  • Preconditions can't be strengthened (a subtype can't demand more of callers).
  • Postconditions can't be weakened (a subtype can't promise less).
  • Invariants of the supertype must be preserved.
  • No new exceptions that callers of the supertype don't expect.

Classic violations:

Java
// 1. Square extends Rectangle: setWidth on a Square must also change height,
//    breaking callers that assume width and height are independent.
void stretch(Rectangle r) { r.setWidth(r.getWidth() * 2); assert r.area() == old * 2; } // fails for Square

// 2. The JDK's own: List.of(...) returns an immutable List; add() throws UnsupportedOperationException.
//    The List interface documents add() as "optional", a deliberate compromise that weakens substitutability.
List<String> xs = List.of("a");
xs.add("b");    // UnsupportedOperationException at run time

// 3. A subclass method that ignores the call ("no-op override"), or throws for inputs the parent accepts.

Fixes: model capabilities separately (ReadableList versus MutableList, as Kotlin does with List and MutableList), make value objects immutable (an immutable Square is a valid Rectangle, because nothing can mutate width independently), or don't use subtyping for the relationship at all.

Type systems check signature variance (chapter 36), but only tests and design can check behavioural substitutability. Contract tests, a single test suite run against every implementation of an interface, are the practical tool (chapter 54).

Values and identity

Object identity

Every object in Java, C#, Python or JS has an identity: it's this particular object, distinct from another with identical fields. Identity is observable through == (Java reference equality), System.identityHashCode, synchronized(obj) and WeakReference.

Two kinds of domain objects follow:

  • Entities have identity that persists through state changes: a Customer with ID 42 is the same customer after changing address. Equality is by ID (and in JPA, carefully, chapter 49).
  • Value objects have no identity: Money(10, EUR) equals any other Money(10, EUR). They're defined entirely by their attributes, so they should be immutable and compared by value.

The JVM pays for identity even when you don't need it: every object has a header (12–16 bytes: a mark word for locking and hashing, plus a class pointer). Compact object headers cut this to 8 bytes: they were experimental in JDK 24, became a product option in JDK 25, and are on by default in JDK 27, and arrays of objects are arrays of pointers. Project Valhalla's value classes (JEP 401) drop identity so the JVM can flatten them into fields and arrays like C structs or C# structs.

Languages with value semantics by default (Go, Rust, C, C++, Zig, C# structs, Swift structs) don't have this split. A struct is its bytes, and you add identity explicitly with an ID field or a pointer.

Value objects

Value objects model concepts like Money, EmailAddress, DateRange, OrderId and Quantity. Using them instead of raw primitives ("primitive obsession") gives you validation at construction, behaviour where it belongs, and type safety:

Java
// Without: easy to swap arguments; no validation
void transfer(String fromIban, String toIban, long cents, String currency) { … }
transfer(to, from, 500, "EUR");      // compiles, wrong direction

// With value objects
public record Iban(String value) {
    public Iban {
        value = value.replace(" ", "").toUpperCase();
        if (!IbanValidator.isValid(value)) throw new IllegalArgumentException("invalid IBAN");
    }
}
public record AccountId(UUID value) {}             // strongly typed IDs: can't pass an OrderId by mistake
void transfer(Iban from, Iban to, Money amount) { … }

Zero-cost wrappers in other languages:

// Newtype pattern: same machine representation as u64, distinct type
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct OrderId(u64);
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct CustomerId(u64);

fn cancel(id: OrderId) { }
// cancel(CustomerId(7));   // compile error: mismatched types

Immutability

An immutable object can't change after construction. Benefits:

  • Thread safety for free: immutable objects can be shared across threads without locks (chapter 38). Java's memory model guarantees that final fields are visible after construction to other threads, provided this doesn't escape the constructor.
  • Safe as map keys and set members: their hashCode can't change while stored (chapter 35).
  • Easier reasoning: no action at a distance, no defensive copies needed when sharing.
  • Caching and sharing: String interning, Integer.valueOf caching, and persistent data structures that share structure between versions.

Costs: creating new objects for each change (cheap for small objects on the JVM, where allocation is a pointer bump and short-lived objects die young, chapter 40), and awkwardness for large, frequently updated aggregates.

How deeply each language supports it:

Language Mechanism Depth
Java final fields, records, List.of/Map.of (unmodifiable), Collections.unmodifiableList (a view, so changes to the backing list show through) Shallow: a final List field can still have its list mutated
Kotlin val, read-only List interface (still mutable underneath if cast), kotlinx.collections.immutable Shallow, interface-level
C# readonly, init accessors, records, ImmutableArray<T>, FrozenDictionary Shallow, plus true immutable collections
C++ const objects, const member functions, const& Deep-ish (transitive through members, not through pointers)
Rust Immutable by default; &T shared borrows forbid mutation (except interior mutability via Cell/RefCell/Mutex, which is explicit) Deep and compiler-enforced
Go No const for structs, no read-only references Convention only (unexported fields + value receivers)
Zig const bindings and []const T pointers Pointer-level
Haskell, Elm, Clojure, Erlang/Elixir All data is immutable; "updates" create new versions sharing structure Total
Python tuple, frozenset, @dataclass(frozen=True) (bypassable via object.__setattr__) Shallow, by convention
Java
// Shallow immutability trap and the fix
public record Team(String name, List<String> members) {
    public Team {
        members = List.copyOf(members);   // defensive copy into an unmodifiable list (also rejects nulls)
    }
}

Persistent data structures (Clojure's vectors and maps, Scala's immutable collections, Haskell's Data.Map, Vavr in Java, im in Rust, Immutable.js) make immutable updates efficient: an "update" returns a new version in O(log n) time that shares most of its nodes with the old one, using hash array mapped tries or balanced trees.

Putting it together: paradigms side by side

The same feature, an order that can be paid or cancelled and produces events, written in four styles:

// OOP + modern Java: encapsulated entity, value objects, sealed events
public final class Order {
    private final OrderId id;
    private Status status = Status.PENDING;
    private final List<OrderEvent> events = new ArrayList<>();

    public Order(OrderId id) { this.id = id; }

    public void pay(Money amount) {
        if (status != Status.PENDING) throw new IllegalStateException("can't pay " + status);
        status = Status.PAID;
        events.add(new OrderPaid(id, amount, Instant.now()));
    }
    public void cancel(String reason) {
        if (status == Status.PAID) throw new IllegalStateException("refund instead");
        status = Status.CANCELLED;
        events.add(new OrderCancelled(id, reason));
    }
    public List<OrderEvent> pullEvents() { var out = List.copyOf(events); events.clear(); return out; }
    enum Status { PENDING, PAID, CANCELLED }
}
sealed interface OrderEvent permits OrderPaid, OrderCancelled {}
record OrderPaid(OrderId id, Money amount, Instant at) implements OrderEvent {}
record OrderCancelled(OrderId id, String reason) implements OrderEvent {}

Each style guards the same invariant ("can't pay twice, can't cancel after payment") with a different mechanism:

  • OOP: encapsulation with run-time checks.
  • FP: a pure function returning a result, with no mutation.
  • Rust: the type system, through typestate.
  • Actors: process isolation and sequential message handling.

Good backend engineers move between these styles deliberately.

Lab: four object-design bugs, reproduced

Each experiment below is a classic design failure reduced to a few lines and run on JDK 21. All four compile without warnings, which is exactly why they reach production.

Experiment 1: the fragile base class

A set that counts how many elements were ever added, written by extending HashSet and, alternatively, by wrapping one:

Java
static class CountingSet<E> extends HashSet<E> {
    int added = 0;
    @Override public boolean add(E e) { added++; return super.add(e); }
    @Override public boolean addAll(Collection<? extends E> c) { added += c.size(); return super.addAll(c); }
}
static class CountingSetByComposition<E> {
    private final Set<E> inner = new HashSet<>(); int added = 0;
    boolean add(E e) { added++; return inner.add(e); }
    boolean addAll(Collection<? extends E> c) { added += c.size(); return inner.addAll(c); }
}
Text
added 3 items → subclass counted 6, composition counted 3

HashSet.addAll happens to be implemented (in AbstractCollection) by calling add for each element, which the subclass also overrides: every item was counted twice. Nothing in HashSet's public contract says so; it's an implementation detail the subclass silently depended on, and a future JDK could change it and "fix" or break the count. The wrapper depends only on the set's public behaviour. This is the example Joshua Bloch uses in Effective Java, and the reason the rule is "design and document for inheritance, or else prohibit it": make classes final unless they're built to be extended.

Experiment 2: a mutable key in a HashMap

Java
Map<Table, String> waiter = new HashMap<>(); Table t = new Table(4); waiter.put(t, "Ravi");
t.number = 7;                                         // the key object is changed after insertion
Text
get(table 7): null | get(table 4): null | containsKey(t): false | size: 1

The entry is still in the map (size 1), but nothing can find it: it was stored in the bucket for hash code 4, and lookups for the same object now compute hash code 7. Not even the original object finds it. Objects used as map keys or set members must be immutable in the fields that equals and hashCode use; records make this the default.

Experiment 3: a Square that isn't a Rectangle

Java
static int resizeTo5x4(Rectangle r) { r.setWidth(5); r.setHeight(4); return r.area(); }
Text
resize to 5×4: Rectangle area 20, Square area 16

Mathematically a square is a rectangle, so Square extends Rectangle looks right. But code written for Rectangle assumes setting the height leaves the width alone, and Square can't honour that promise: passing a Square silently breaks correct code. That's a violation of the Liskov substitution principle: a subtype must be usable wherever its parent is, without surprises. The fixes are to make both immutable values (a square is then just a rectangle whose sides happen to be equal), or not to relate them by inheritance at all.

Experiment 4: equals without hashCode

Java
static final class Dish { final String name; … equals compares name … /* no hashCode */ }
Set<Dish> set = new HashSet<>(); set.add(new Dish("dosa")); set.add(new Dish("dosa"));
Text
equals says equal: true | HashSet size after adding 'dosa' twice: 2 | contains: false

The contract says equal objects must have equal hash codes. Without an overridden hashCode, each object gets an identity-based one, so two "equal" dishes land in different buckets: the set holds duplicates and can't find a dish it contains. Generate both together (records do; IDEs and Lombok do; tests with EqualsVerifier check the contract), and never override one without the other.

Try it yourself

  1. Make CountingSet correct without changing to composition. What did you have to know about HashSet's internals, and why is that a bad sign?
  2. Rewrite experiment 2's Table as a record and try to reproduce the bug.
  3. Implement Rectangle and Square as immutable records with a sealed interface Shape, and write area as a pattern-matching switch.
  4. Write the same PaymentMethod design in Go (interfaces satisfied implicitly) and Rust (traits, and alternatively an enum with match). Which design does each language nudge you towards?

Revision sheet: OOP and its alternatives

Key ideas

  • OOP bundles state with the operations allowed to change it; the goal is protecting invariants and managing change in large codebases.
  • Encapsulation (private state, intention-revealing methods, defensive copies), abstraction (interfaces as capabilities), polymorphism (dynamic dispatch), inheritance (use sparingly, design for it or forbid it).
  • Composition over inheritance; delegation; small interfaces; dependency on abstractions.
  • Liskov substitution: subtypes must keep their parents' promises (preconditions no stronger, postconditions no weaker, invariants preserved).
  • Expression problem: interfaces make new kinds easy; sealed types plus pattern matching make new operations easy (with exhaustiveness checks); visitors and type classes are other answers.
  • Dispatch: single dispatch in Java/C#; multiple dispatch (Julia, CLOS); traits and type classes (Rust, Haskell); structural interfaces (Go, TypeScript).
  • Values vs entities: immutable value objects compared by value; entities with identity; records for values.
  • Other paradigms: procedural, functional (data + functions, immutability), actor model (Erlang/Akka), data-oriented design.

Numbers to remember

  • Lab: the HashSet subclass counted 6 for 3 additions; a mutated key made a map entry unreachable (size 1, lookups null); a Square produced area 16 instead of 20.

Pitfalls

  • Inheriting for code reuse; deep hierarchies; non-final classes not designed for extension.
  • Getters returning internal mutable collections; setters for everything (anaemic models).
  • Mutable fields in equals/hashCode; equals without hashCode.
  • instanceof chains where polymorphism or sealed switches belong.
  • God classes and "Manager"/"Util" classes with no cohesive responsibility.

Glossary

  • Invariant: a condition on an object's state that always holds.
  • Dynamic dispatch: selecting a method implementation by the receiver's runtime class.
  • Sealed type: a type whose permitted subtypes are fixed and known to the compiler.
  • LSP: the Liskov substitution principle.
  • Value object: an immutable object defined by its attributes.
  • Delegation: forwarding a call to a contained object.