SOLID Principles
Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion — each with a realistic violation, the refactor, how to spot it in code review, and when applying it is overkill.
S — Single Responsibility Principle
A class should have one reason to change — it should serve one actor.
// ❌ Three reasons to change: business rules, persistence, presentation
class Invoice {
long total() { /* tax and discount rules */ return 0; }
void saveToDatabase() { /* SQL */ }
String toPdf() { /* layout */ return ""; }
}
// ✅ Separate responsibilities
class Invoice { long total() { return 0; } } // finance rules
class InvoiceRepository { void save(Invoice i) { } } // persistence
class InvoicePdfRenderer { byte[] render(Invoice i) { return new byte[0]; } } // presentation
Smells: class names with "And"/"Manager"/"Utils"; methods that touch unrelated fields; changes for different teams landing in the same file; huge test setup.
O — Open/Closed Principle
Software entities should be open for extension, closed for modification.
// ❌ every new discount type edits this method (and risks breaking others)
class DiscountCalculator {
long apply(Order o, String type) {
if (type.equals("PERCENT")) return o.total() * 90 / 100;
else if (type.equals("FLAT")) return o.total() - 500;
else if (type.equals("BOGO")) { /* ... */ }
return o.total();
}
}
// ✅ new discounts = new classes
interface Discount { long apply(Order o); }
class PercentDiscount implements Discount {
private final int pct;
PercentDiscount(int pct) { this.pct = pct; }
public long apply(Order o) { return o.total() * (100 - pct) / 100; }
}
class FlatDiscount implements Discount {
private final long amount;
FlatDiscount(long amount) { this.amount = amount; }
public long apply(Order o) { return Math.max(0, o.total() - amount); }
}
class Checkout {
long finalPrice(Order o, Discount d) { return d.apply(o); }
}
from typing import Protocol
class Discount(Protocol):
def apply(self, total: int) -> int: ...
class PercentDiscount:
def __init__(self, pct: int): self.pct = pct
def apply(self, total: int) -> int: return total * (100 - self.pct) // 100
class FlatDiscount:
def __init__(self, amount: int): self.amount = amount
def apply(self, total: int) -> int: return max(0, total - self.amount)
def final_price(total: int, discount: Discount) -> int:
return discount.apply(total)
L — Liskov Substitution Principle
Objects of a subtype must be substitutable for objects of the base type without altering correctness.
// ❌ violates LSP
class Bird { void fly() { /* ... */ } }
class Penguin extends Bird {
@Override void fly() { throw new UnsupportedOperationException(); } // surprise!
}
// ✅ model capabilities separately
interface Bird { void eat(); }
interface FlyingBird extends Bird { void fly(); }
class Sparrow implements FlyingBird { public void eat() {} public void fly() {} }
class Penguin implements Bird { public void eat() {} }
LSP rules (design by contract): a subtype may not strengthen preconditions (accept less), may not weaken postconditions (promise less), must preserve invariants, and must not throw new kinds of exceptions callers don't expect.
I — Interface Segregation Principle
Clients should not be forced to depend on methods they don't use.
// ❌ fat interface
interface Machine { void print(Doc d); void scan(Doc d); void fax(Doc d); }
class BasicPrinter implements Machine {
public void print(Doc d) { }
public void scan(Doc d) { throw new UnsupportedOperationException(); } // forced
public void fax(Doc d) { throw new UnsupportedOperationException(); }
}
// ✅ role interfaces
interface Printer { void print(Doc d); }
interface Scanner { void scan(Doc d); }
interface Fax { void fax(Doc d); }
class BasicPrinter implements Printer { public void print(Doc d) { } }
class OfficeMachine implements Printer, Scanner, Fax { /* ... */ }
D — Dependency Inversion Principle
High-level modules should not depend on low-level modules; both should depend on abstractions.
// ✅ the service owns the abstraction it needs; implementations are injected
public interface OrderRepository {
Optional<Order> find(String id);
void save(Order order);
}
public interface PaymentGateway {
PaymentResult charge(String customerId, long amountMinor, String idempotencyKey);
}
public final class OrderService {
private final OrderRepository orders;
private final PaymentGateway payments;
public OrderService(OrderRepository orders, PaymentGateway payments) { // constructor injection
this.orders = orders;
this.payments = payments;
}
public void pay(String orderId) {
Order o = orders.find(orderId).orElseThrow();
PaymentResult r = payments.charge(o.customerId(), o.total(), "pay:" + orderId);
o.markPaid(r.reference());
orders.save(o);
}
}
// in tests: new OrderService(new InMemoryOrderRepository(), new FakePaymentGateway());
class OrderService:
def __init__(self, orders: "OrderRepository", payments: "PaymentGateway"):
self.orders, self.payments = orders, payments
def pay(self, order_id: str) -> None:
order = self.orders.find(order_id)
ref = self.payments.charge(order.customer_id, order.total, f"pay:{order_id}")
order.mark_paid(ref)
self.orders.save(order)
Summary table
| Principle | Ask yourself | Common fix |
|---|---|---|
| SRP | Does this class change for more than one reason? | split by actor/responsibility |
| OCP | Do I edit this switch every time a variant is added? | polymorphism, strategy, registry |
| LSP | Can every subtype honestly stand in for its parent? | composition, smaller interfaces |
| ISP | Are implementers forced to stub methods? | role interfaces |
| DIP | Does business logic new up databases/HTTP clients? | interfaces + injection |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.