LLD

Design Principles

Composition over inheritance

Prefer holding an object over extending a class, most of all when a class varies in more than one way. We price cab rides by car and by plan, add SUVs and airport rides, and see what that change costs with subclasses and with parts.

A cab app lets a rider pick a car, Mini or Sedan, and a plan, solo or shared. The first version has one class for each combination. Then the company adds SUVs and airport rides, and the number of classes grows quickly.

Composition over inheritance says that we prefer holding an object over extending a class. This matters most when a class varies in more than one way: we build it from parts it holds, instead of writing a subclass for every combination.

The principle

Inheritance and composition are two ways to reuse code. With inheritance, a class extends another class and gets its fields and methods. With composition, a class keeps other objects in its fields and calls them. The principle says to prefer composition when both would work, for two reasons:

  • A class has one parent. A class that varies in two ways needs a subclass for each pair, and the code for one way is copied into each of them.
  • A subclass gets every public method. Java's own Stack extends Vector, so a stack also has add(index, item) and remove(index). Any caller can put an item in the middle of the stack.

What it does not say

It does not say "never use inheritance". Inheritance fits a true is-a relationship with a stable base class. PaymentDeclinedException extends RuntimeException is a good subclass: it behaves like a runtime exception everywhere, and the base class does not change under it. Is-a means the subclass keeps every promise of its parent, as the Liskov Substitution Principle page shows. The Template Method pattern also uses inheritance on purpose.

Example: pricing cab rides

A Mini costs $3.00 plus $1.50 a km, and a Sedan costs $4.00 plus $2.00 a km. The code keeps money in cents, so $1.50 is 150. A shared ride costs 30% less. The first version has a subclass of Ride for each car:

abstract class Ride {    protected final int km;     Ride(int km) {        this.km = km;    }     abstract long fareCents();} class MiniRide extends Ride {    MiniRide(int km) {        super(km);    }     @Override    long fareCents() {        return 300 + km * 150L; // $3.00 base, $1.50 a km    }}

A shared Mini extends MiniRide and takes 30% off:

class SharedMiniRide extends MiniRide {    SharedMiniRide(int km) {        super(km);    }     @Override    long fareCents() {        return super.fareCents() * 70 / 100; // 30% off for sharing the cab    }}

SedanRide and SharedSedanRide are the same with the Sedan's rates. SharedSedanRide must extend SedanRide to get those rates, so it cannot also extend SharedMiniRide. It copies the * 70 / 100 line.

The change request

The company adds SUVs at $5.00 plus $2.50 a km, solo or shared. It also adds airport rides for every car: the normal fare for that car plus a $5.00 airport fee. SUVs need SuvRide and SharedSuvRide. Airport rides need AirportMiniRide, AirportSedanRide and AirportSuvRide. Four classes become nine. The 30% rule is now written in three classes, and the $5.00 fee in three more. If the shared discount changes, three classes change, and a missed one keeps charging the old price for that car.

One subclass per pair
Each cell is a subclass. The rows are car types and the columns are plans. The SUV row and the Airport column, outlined in amber, are the change: five new classes, nine in all. Every Shared cell copies the 30% rule and every Airport cell copies the $5.00 fee.Each cell is a subclass. The rows are car types and the columns are plans. The SUV row and the Airport column, outlined in amber, are the change: five new classes, nine in all. Every Shared cell copies the 30% rule and every Airport cell copies the $5.00 fee.
Two lists that vary make a grid of classes. Each cell is a subclass. The rows are car types and the columns are plans. The SUV row and the Airport column, outlined in amber, are the change: five new classes, nine in all. Every Shared cell copies the 30% rule and every Airport cell copies the $5.00 fee.

Following the principle

A ride is now built from two parts. Car types differ only in their numbers, and every car type is known when the code is written, so CarType is an enum with one constant for each car. Its metered fare is the base fare plus the rate per km:

enum CarType {    MINI(300, 150),    SEDAN(400, 200);     private final long baseFareCents;    private final long centsPerKm;     CarType(long baseFareCents, long centsPerKm) {        this.baseFareCents = baseFareCents;        this.centsPerKm = centsPerKm;    }     long meteredFareCents(int km) {        return baseFareCents + km * centsPerKm;    }}

Plans differ in their rule, so each plan is a class behind one interface. SoloFare returns the metered fare, and SharedFare takes 30% off it:

interface FarePlan {    long fareCents(CarType car, int km);} final class SharedFare implements FarePlan {    @Override    public long fareCents(CarType car, int km) {        return car.meteredFareCents(km) * 70 / 100; // 30% off for sharing the cab    }}

Ride holds a car type and a plan, and asks the plan for the fare:

final class Ride {    private final CarType car;    private final FarePlan plan;    private final int km;     Ride(CarType car, FarePlan plan, int km) {        this.car = car;        this.plan = plan;        this.km = km;    }     long fareCents() {        return plan.fareCents(car, km);    }}

Now the same change request arrives. The SUV is one new constant in CarType:

    MINI(300, 150),    SEDAN(400, 200),    SUV(500, 250); // the one new constant

The airport ride is one new class, AirportFare, whose fareCents adds $5.00 to the metered fare. Ride, SoloFare and SharedFare do not change. Every car works with every plan, so a 10 km shared SUV ride, new Ride(CarType.SUV, new SharedFare(), 10), costs $21.00 with no new class. The 30% rule is written once, in SharedFare. A fourth car type would add one constant, not three classes.

The same change, after
Ride uses a yellow CarType enum and a purple FarePlan interface. The three plans implement FarePlan. The dashed amber outlines mark what the change added: the SUV constant and the AirportFare class. Ride, the enum's method and the two old plans are unchanged.Ride uses a yellow CarType enum and a purple FarePlan interface. The three plans implement FarePlan. The dashed amber outlines mark what the change added: the SUV constant and the AirportFare class. Ride, the enum's method and the two old plans are unchanged.
A ride holds a car type and a plan, and each list grows on its own. Ride uses a yellow CarType enum and a purple FarePlan interface. The three plans implement FarePlan. The dashed amber outlines mark what the change added: the SUV constant and the AirportFare class. Ride, the enum's method and the two old plans are unchanged.

When not to

Composition has a cost too. There are more small objects, and a reader has to follow a field to see what a method does. If a type varies in only one way, and the base class is small and stable, one level of subclasses is shorter and clearer. We also do not add a FarePlan interface while the app has only one way to price a ride. We can add it on the day a second plan appears.

In an interview

Class names that join one word from each of two lists, like SharedSedanRide, show that a class varies in two ways. In a low-level design (LLD) round, we name the two ways, make each one a part the main object holds, and say which list we expect to grow. The Bridge pattern page fixes the same grid of classes in a food delivery map, and the Parking Lot holds its fee rule as an object.

Common mistakes:

  • Extending a class only to reuse its code. The subclass gets every public method of the parent, as Stack got add(index, item) from Vector.
  • A subclass for each combination. The classes grow as rows times columns, and each rule is copied along a row or a column.
  • Saying inheritance is always wrong. A true is-a with a stable base, like an exception type, is a fine subclass.

Summary

  • Prefer holding an object over extending a class. When a class varies in more than one way, build it from parts it holds instead of a subclass for each combination.
  • Subclasses for every pair grow as rows times columns, and they copy each rule.
  • With parts, a new car type or plan is one addition, and it works with every existing part.
  • Inheritance is still right for a true is-a relationship with a stable base class.

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

Article

Send feedback

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

How do you feel about oneby7?

Sign in to oneby7

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

New here? This creates your account too.