Design Principles Beyond SOLID
DRY, KISS, YAGNI, Law of Demeter, composition over inheritance, high cohesion and low coupling, separation of concerns, GRASP responsibility assignment, dependency injection, immutability, fail-fast, tell-don't-ask, and designing for testability.
The everyday principles
| Principle | One line | Smell when violated |
|---|---|---|
| DRY | one source of truth per piece of knowledge | the same validation rule in 4 places |
| KISS | simplest thing that works | 5 layers for a CRUD endpoint |
| YAGNI | build for today's requirements | plugin system with one plugin |
| Separation of concerns | different concerns in different modules | SQL inside UI code |
| Composition over inheritance | has-a beats is-a for varying behaviour | deep class hierarchies |
| Law of Demeter | talk to friends, not strangers | a.getB().getC().doX() |
| Tell, don't ask | ask objects to act, don't pull their data | if (acct.getBalance() > x) acct.setBalance(...) |
| Fail fast | detect invalid state at the boundary, loudly | nulls propagating deep before crashing |
| Principle of least astonishment | APIs behave as users expect | get() that mutates |
| Program to interfaces | depend on abstractions | ArrayList<String> list parameters |
| Encapsulate what varies | isolate the parts likely to change | if/else on types scattered around |
Tell, don't ask
Java
// ❌ ask: logic about Account lives outside Account
if (account.getBalance() >= amount) {
account.setBalance(account.getBalance() - amount);
}
// ✅ tell: the object protects its own invariant
account.withdraw(amount); // throws InsufficientFunds
Law of Demeter
Java
// ❌ caller knows Order → Customer → Address structure
String city = order.getCustomer().getAddress().getCity();
// ✅ expose what the caller actually needs
String city = order.shippingCity();
Cohesion and coupling
GRASP in practice
| Pattern | Question it answers | Example (parking lot) |
|---|---|---|
| Information Expert | who has the data? | ParkingFloor.findFreeSpot(type) |
| Creator | who creates X? | ParkingLot creates Tickets for its spots |
| Controller | who handles the use case? | EntryGateController.handleArrival() |
| Polymorphism | how to vary by type? | PricingStrategy per vehicle type |
| Pure Fabrication | where does non-domain logic go? | TicketRepository, PaymentProcessor |
| Indirection | how to decouple? | NotificationGateway adapter |
| Protected Variations | how to shield from change? | PaymentGateway interface over providers |
Dependency injection without a framework
Java
// composition root: the only place that knows concrete classes
public class App {
public static void main(String[] args) {
DataSource ds = Db.connect(System.getenv("DATABASE_URL"));
OrderRepository repo = new PostgresOrderRepository(ds);
PaymentGateway gateway = new StripeGateway(System.getenv("STRIPE_KEY"));
OrderService service = new OrderService(repo, gateway);
new HttpServer(new OrderController(service)).start(8080);
}
}
Constructor injection is preferred: dependencies are explicit, objects are fully initialised and can be immutable, and tests pass fakes directly.
Immutable value objects
public record Money(long amountMinor, String currency) {
public Money {
if (amountMinor < 0) throw new IllegalArgumentException("negative money");
Objects.requireNonNull(currency);
}
public Money plus(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
return new Money(amountMinor + other.amountMinor, currency);
}
}
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
amount_minor: int
currency: str
def __post_init__(self):
if self.amount_minor < 0:
raise ValueError("negative money")
def plus(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("currency mismatch")
return Money(self.amount_minor + other.amount_minor, self.currency)
Designing for testability
- Inject dependencies (clock, random, I/O) —
Clockobjects instead ofSystem.currentTimeMillis(). - Keep business logic pure where possible (functional core, imperative shell).
- Small classes with clear contracts.
- Avoid static global state and singletons holding mutable state.
Domain-driven design vocabulary (useful in LLD and HLD)
| Term | Meaning |
|---|---|
| Entity | has identity that persists over time (Order #9) |
| Value object | defined only by its values, immutable (Money, Address) |
| Aggregate | cluster of objects treated as one consistency boundary, accessed via its root (Order with its lines) |
| Repository | collection-like access to aggregates |
| Domain service | operation that doesn't belong to one entity (TransferService) |
| Domain event | something meaningful that happened (OrderPlaced) |
| Bounded context | a boundary within which a model is consistent (Billing's "Customer" ≠ Support's "Customer") |
| Ubiquitous language | shared vocabulary between developers and domain experts |
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.