SysDesignAtlas

Objects, in Practice

The handful of object-oriented ideas an LLD interview actually tests — what an object is for, why you should hold objects rather than inherit from them, and where interfaces belong.

LLDMedium9 min readooplldfundamentals
Confidence

Nobody will ask you to define polymorphism. They will ask you to design something and then watch whether your classes have any point to them. This page covers only the ideas that change your answer.

#An object protects a rule

The textbook says an object is "data plus behaviour". That's true but not useful. Here's the useful version:

An object exists to protect a rule about its data.

An invariant is the word for such a rule — something that must always be true, no matter what code runs. "A bank balance is never negative" is an invariant.

java
// Not really an object. It's a box of data with a class keyword.
class Account {
    public double balance;
}

// An object: the rule lives with the data, and there is no way in
// that skips the check.
class Account {
    private long balanceMinor;   // money in paise/cents, never a double

    void withdraw(long amount) {
        if (amount <= 0)
            throw new IllegalArgumentException("amount must be positive");
        if (amount > balanceMinor) throw new InsufficientFundsException(id, amount);
        balanceMinor -= amount;
    }

    long balance() { return balanceMinor; }
}

Why the second one is better: no code anywhere can make the balance negative, because no code can reach the field. In the first version the rule has to be repeated by every piece of code that touches balance — which means, in practice, that some of them forget.

Two things that follow, worth saying when they come up:

  • Getters and setters are not encapsulation. A getBalance/setBalance pair is just a public field with extra steps. Expose actions (withdraw, deposit), not fields.
  • Tell, don't ask. If you pull data out of an object to make a decision about that object, the decision belongs inside it. if (order.getItems().isEmpty()) repeated in five places wants to be order.isEmpty().

#Prefer holding an object to inheriting from one

This is the highest-value idea on the page, because the classic interview problems are built to reward it.

Some vocabulary first:

  • Inheritance is class Car extends Vehicle. Car is a Vehicle and gets its behaviour automatically.
  • Composition is class Order { private DiscountPolicy discount; }. Order has a DiscountPolicy and calls it.

Inheritance gives you exactly one way for things to differ: each subclass is one variety. As soon as your problem has two independent ways to differ — say, notifications differ by channel (email, SMS, push) and separately by priority (urgent, normal) — you need one subclass for every combination, and the number of classes multiplies:

   With inheritance, two things vary:      With composition, two things vary:

   Notification                            Notification
     ├── EmailUrgent                          ├── Channel   (email | sms | push)
     ├── EmailNormal                          └── Priority  (urgent | normal)
     ├── SmsUrgent
     ├── SmsNormal                          3 + 2 = 5 classes
     ├── PushUrgent                         adding WhatsApp = 1 more
     └── PushNormal
                                            Add a third thing (4 languages):
   3 × 2 = 6 classes                          inheritance → 24 classes
   adding WhatsApp = 2 more                   composition → 9

The rule interviewers listen for: inherit only when the child really is a kind of the parent, and you expect the family to stay one level deep (no subclasses of subclasses). Otherwise, hold a reference — give the class a field pointing at the other object and call it.

java
// is-a: a Car is a Vehicle. Fine — one axis, and a Car works
// anywhere a Vehicle is expected.
class Car extends Vehicle { }

// has-a: an Order is not a kind of DiscountPolicy. So hold one.
class Order {
    private final DiscountPolicy discount;      // can be swapped at runtime
    private final List<OrderLine> lines;

    Money total() { return discount.apply(subtotal()); }
}

#Interfaces go where things genuinely vary

An interface is a list of method names with no code behind them. Several classes can implement it, and code that uses the interface doesn't care which one it got.

An interface earns its place when there is — now or clearly soon — more than one implementation. Not before. A UserServiceInterface with a single UserServiceImpl behind it is clutter: it adds a file and a layer of indirection while giving you no choice to make. Experienced interviewers notice.

How to find the real ones, in order:

  1. Reread the requirements looking for the words "different", "depending on", "either… or", "configurable", "for now". Each one marks a place where things vary.
  2. Ask what the interviewer is likely to add later. "Now support another payment method" is the most common follow-up there is — so payment varies.
  3. Everything else stays an ordinary class until you have a reason.
java
interface PricingStrategy {                 // varies: how the fee is worked out
    Money price(Duration parked, VehicleSize size);
}

interface PaymentMethod {                   // varies: how the money moves
    PaymentResult charge(Money amount);
}

// Not varying: there is only one way to be a ticket.
final class Ticket { /* ... */ }

#Two kinds of object: entities and values

This distinction takes one sentence to explain and immediately makes a design look considered.

EntityValue object
IdentityHas an ID. Two entities with identical fields are still two different thingsIs its fields. Two with identical fields are the same thing
Changes?Usually changes over its lifeNever changes once created
ExamplesUser, Ticket, ParkingSpot, OrderMoney, TimeSlot, Address, Coordinates
ComparingCompare IDsCompare every field

Two people called Ravi Sharma are two users, even with identical details — so User is an entity. ₹50 is ₹50 wherever it came from — so Money is a value.

java
// A value object: cannot change, checks itself, compared by value.
record Money(long minorUnits, Currency currency) {
    Money {
        if (currency == null)
            throw new IllegalArgumentException("currency required");
    }
    Money plus(Money other) {
        if (!currency.equals(other.currency)) throw new CurrencyMismatchException();
        return new Money(minorUnits + other.minorUnits, currency);
    }
}

Two payoffs worth mentioning out loud. Value objects are automatically safe to share between threads, because nothing can change them. And they remove a whole family of bugs where one piece of code modifies an object while another piece is still using it — for example, a price that changes underneath an order that was halfway through totalling it. When the threading question arrives — and it will — "most of my model is immutable (can't be changed after creation), so the only shared data that changes is X" is a strong opening. See Threads and races.

#Enums can hold behaviour

A small trick that makes your code look fluent, especially for pricing and for objects with states. Instead of storing a bare enum and switching on it elsewhere, put the data and the logic on the enum itself:

java
enum VehicleSize {
    MOTORCYCLE(1), COMPACT(2), LARGE(3);

    private final int units;
    VehicleSize(int units) { this.units = units; }

    boolean fitsIn(SpotSize spot) { return units <= spot.units(); }
}

The alternative is a switch (size) copied into every file that needs to know whether a vehicle fits — and each new size means finding and editing all of them. That's exactly the problem the Open/Closed principle exists to prevent. See SOLID.

#Four questions to ask of every class you draw

Ten seconds each, and they catch most bad designs before you commit them to the board.

  1. What is its one job? If you need the word "and" to answer, split it.
  2. What rule does it protect? If there isn't one, it may just be a value object — fine, but say so.
  3. What does it depend on, and is that a concrete class or an interface? Depending on a concrete class (a specific implementation like SmtpMailer) is fine unless that thing really varies — then it should be an interface.
  4. If the interviewer adds a feature, does this class change, or does a new class appear? "A new class appears" is the answer you want.

#Check yourself

What is an object for, in design terms?Show answer
Protecting a rule (an invariant) about its data: keep the field private and expose actions like withdraw that enforce the rule in one place, so no caller can bypass it.
Why aren't getters and setters encapsulation?Show answer
A get/set pair is a public field with extra steps — the rule still has to be repeated by every caller. Expose actions (withdraw, deposit), not fields.
What does "tell, don't ask" mean?Show answer
If you pull data out of an object to decide something about it, move the decision inside: order.isEmpty() instead of checking order.getItems().isEmpty() in five places.
When should you inherit, and when compose?Show answer
Inherit only for a genuine is-a with a family that stays about one level deep. Otherwise hold a reference — inheritance allows one dimension of variation and multiplies classes when there are two.
What is the better opening for parking-lot vehicles?Show answer
If vehicle types differ only by the spot size they need, give Vehicle a VehicleSize field instead of Car, Bike and Truck subclasses; subclass only if behaviour differs.
When does an interface earn its place?Show answer
When there is, or will clearly be, more than one implementation. Look for "different", "depending on", "either/or", "configurable", "for now", and likely follow-ups such as another payment method.
Entity versus value object?Show answer
An entity has an ID and changes over time; two with identical fields are still different (User, Order). A value object is its fields, never changes and compares by value (Money, TimeSlot) — and is safe to share between threads.
Name the four questions to ask of every class.Show answer
What is its one job (no "and")? What rule does it protect? Does it depend on a concrete class or an interface — and does that thing really vary? Does a new feature change it or add a new class?

#What to carry forward

  • An object protects a rule about its data — expose actions, not fields.
  • Prefer holding an object to inheriting from one; inheritance handles only one dimension of variation.
  • Interfaces go only where things genuinely vary, now or in a likely follow-up.
  • Separate entities (identity, change) from value objects (immutable, compared by value).
  • Enums can carry behaviour, replacing switches copied across files.
00:00
/ 9m