Low-level design rounds ask you to model a small system in classes and write working code. Interviewers look for code that is easy to extend and test. SOLID names the habits that make that true. Use them as a checklist, not a religion.
S: single responsibility
A class should have one reason to change. If a new CSV format, a new tax rule and a new email provider would all edit the same class, split it.
// Before: three reasons to change in one class (format, pricing rules, email provider).
class InvoiceService {
Invoice parse(String csv) { /* ... */ }
long totalCents(Invoice invoice) { /* ... */ }
void email(Invoice invoice) { /* ... */ }
}
// After: each class changes for one reason.
class InvoiceParser { Invoice parse(String csv) { /* ... */ } }
class InvoicePricer { long totalCents(Invoice invoice) { /* ... */ } }
class InvoiceMailer { void send(Invoice invoice) { /* ... */ } }
O: open for extension, closed for modification
Add behaviour by adding code, not by editing working code. A switch over types that grows with every feature is the usual warning sign.
interface Discount { long apply(long cents); }
record PercentOff(int percent) implements Discount {
public long apply(long cents) { return cents * (100 - percent) / 100; }
}
record FlatOff(long off) implements Discount {
public long apply(long cents) { return Math.max(0, cents - off); }
}
// Checkout never changes when marketing invents a new discount type.
long checkout(long cents, List<Discount> discounts) {
for (Discount d : discounts) cents = d.apply(cents);
return cents;
}
L: Liskov substitution
A subtype must work anywhere its parent type is expected, without surprises. If a subclass throws on a method its parent supports, or quietly ignores it, the inheritance is wrong.
// Violates LSP: code written against List expects add() to work.
class ReadOnlyList<T> extends ArrayList<T> {
@Override public boolean add(T t) { throw new UnsupportedOperationException(); }
}
// Honest types instead: expose only what the object can actually do.
interface ReadableList<T> { T get(int i); int size(); }
I: interface segregation
Don't make classes implement methods they don't need. Several small interfaces beat one large one.
// A fat interface forces a basic printer to fake scan() and fax().
interface MultiFunctionDevice { void print(Doc d); void scan(Doc d); void fax(Doc d); }
// Small interfaces, combined only where needed.
interface Printer { void print(Doc d); }
interface Scanner { void scan(Doc d); }
class OfficeCopier implements Printer, Scanner { /* ... */ }
class HomePrinter implements Printer { /* ... */ }
D: dependency inversion
High-level code depends on interfaces, and the concrete classes are passed in (dependency injection). This is the principle that makes code testable: in tests you pass a fake.
interface PaymentGateway { Receipt charge(String customerId, long cents); }
class OrderService {
private final PaymentGateway payments; // depends on the abstraction
OrderService(PaymentGateway payments) { this.payments = payments; }
Receipt place(Order order) { return payments.charge(order.customerId(), order.totalCents()); }
}
// Production: new OrderService(new StripeGateway(apiKey))
// Tests: new OrderService(new FakeGateway())
The six patterns worth knowing
Most LLD problems need only these. Name the pattern when you use it, and say what it buys you.
Strategy
Swap an algorithm without changing its caller. Use it for pricing rules, routing, retry policies, parking-spot allocation, elevator dispatch.
interface RoutingStrategy { Route route(Point from, Point to); }
class FastestRoute implements RoutingStrategy { /* ... */ }
class AvoidTolls implements RoutingStrategy { /* ... */ }
class Navigator {
private RoutingStrategy strategy;
void setStrategy(RoutingStrategy s) { this.strategy = s; } // swap at runtime
Route navigate(Point a, Point b) { return strategy.route(a, b); }
}Factory
Put the decision of which class to create in one place. Use it for picking an implementation by configuration or input type.
interface Sender { void send(String userId, String message); }
final class Senders {
static Sender forChannel(Channel channel) {
return switch (channel) {
case EMAIL -> new EmailSender();
case SMS -> new SmsSender();
case PUSH -> new PushSender();
};
}
}Observer
Let many listeners react to an event without the source knowing them. Use it for domain events (order placed → reserve stock, send email), UI updates.
interface OrderListener { void onPlaced(Order order); }
class OrderEvents {
private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
void subscribe(OrderListener l) { listeners.add(l); }
void placed(Order o) { listeners.forEach(l -> l.onPlaced(o)); }
}
// events.subscribe(inventory::reserve); events.subscribe(mailer::sendConfirmation);Builder
Construct an object with many optional fields readably, and validate it once at the end. Use it for requests, configs, immutable value objects.
Alert alert = Alert.builder()
.service("payments")
.severity(Severity.CRITICAL)
.label("region", "ap-south-1")
.dedupeWindow(Duration.ofMinutes(5))
.build(); // build() validates, then returns an immutable AlertDecorator
Add behaviour by wrapping an object in another with the same interface. Use it for caching, logging, metrics, retries. Java's BufferedInputStream is one.
interface Store { byte[] get(String key); }
class CachingStore implements Store {
private final Store inner;
private final Map<String, byte[]> cache = new ConcurrentHashMap<>();
CachingStore(Store inner) { this.inner = inner; }
public byte[] get(String key) { return cache.computeIfAbsent(key, inner::get); }
}
// Same interface, layered behaviour: new MetricsStore(new CachingStore(new S3Store()))Adapter
Make a class with the wrong interface fit the one your code expects. Use it for wrapping third-party SDKs so they can be swapped and faked in tests.
// Third-party SDK with its own shape.
class TwilioClient { MessageResult create(String to, String from, String body) { /* ... */ } }
// Our interface; the rest of the code never sees Twilio.
class TwilioSmsSender implements SmsSender {
private final TwilioClient client;
private final String fromNumber;
TwilioSmsSender(TwilioClient client, String fromNumber) { this.client = client; this.fromNumber = fromNumber; }
public void send(String phone, String text) { client.create(phone, fromNumber, text); }
}
Why Singleton is usually a mistake
A classic Singleton (Config.getInstance()) is global state in disguise. Callers hide their dependency on it, tests can't replace it, and its state leaks between tests. Lazy initialisation adds threading bugs on top. It's reasonable for something that really is one per process and holds no state that matters to behaviour, such as a logger or immutable configuration loaded once at startup. Even then, it's better to create one instance at startup and inject it, so you get "only one" without the global access.
Composition over inheritance
Inheritance fixes a combination of behaviours at compile time, and the number of subclasses multiplies. Composition builds combinations at runtime from small parts that each do one thing.
// Inheritance: one subclass per combination, and it multiplies with every new channel.
class EmailNotifier { void notify(User u, String msg) { /* ... */ } }
class EmailAndSmsNotifier extends EmailNotifier { /* ... */ }
class EmailSmsAndPushNotifier extends EmailAndSmsNotifier { /* ... */ }
// Composition: a notifier has channels; combinations are just lists.
interface Channel { void send(User u, String msg); }
class Notifier {
private final List<Channel> channels;
Notifier(List<Channel> channels) { this.channels = List.copyOf(channels); }
void notify(User u, String msg) { channels.forEach(c -> c.send(u, msg)); }
}
// new Notifier(List.of(new Email(), new Push()))
Use inheritance for a true "is a" relationship with a stable parent. Use composition when you're combining behaviours.
Interview checklist
- Have a real example of each SOLID principle from code you've written.
- Have one use case for each of the six patterns.
- Explain why Singleton is usually a mistake, and the exception.
- Show the same design with inheritance and with composition.
Exercise
Take a class you've written that does too much. Split it along SRP lines, inject its dependencies (DIP), and replace one switch on a type with a strategy (OCP). Then write down which of the six patterns your result uses.
Do it by hand
Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.
Further reading
- Eric Freeman and Elisabeth Robson, Head First Design Patterns (O'Reilly). The friendliest introduction to the classic patterns.
- Refactoring.Guru: design patterns, with diagrams and Java examples for each pattern.
- Joshua Bloch, Effective Java. Idiomatic Java, including builders, immutability and concurrency.