{}DSA Atlas

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.

Intermediate5 interview questions

The everyday principles

PrincipleOne lineSmell when violated
DRYone source of truth per piece of knowledgethe same validation rule in 4 places
KISSsimplest thing that works5 layers for a CRUD endpoint
YAGNIbuild for today's requirementsplugin system with one plugin
Separation of concernsdifferent concerns in different modulesSQL inside UI code
Composition over inheritancehas-a beats is-a for varying behaviourdeep class hierarchies
Law of Demetertalk to friends, not strangersa.getB().getC().doX()
Tell, don't askask objects to act, don't pull their dataif (acct.getBalance() > x) acct.setBalance(...)
Fail fastdetect invalid state at the boundary, loudlynulls propagating deep before crashing
Principle of least astonishmentAPIs behave as users expectget() that mutates
Program to interfacesdepend on abstractionsArrayList<String> list parameters
Encapsulate what variesisolate the parts likely to changeif/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

Tightly coupled every module knows every other's internals Loosely coupled stable interface modules depend on a small contract
Aim for high cohesion inside modules and low coupling between them.

GRASP in practice

PatternQuestion it answersExample (parking lot)
Information Expertwho has the data?ParkingFloor.findFreeSpot(type)
Creatorwho creates X?ParkingLot creates Tickets for its spots
Controllerwho handles the use case?EntryGateController.handleArrival()
Polymorphismhow to vary by type?PricingStrategy per vehicle type
Pure Fabricationwhere does non-domain logic go?TicketRepository, PaymentProcessor
Indirectionhow to decouple?NotificationGateway adapter
Protected Variationshow 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) — Clock objects instead of System.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)

TermMeaning
Entityhas identity that persists over time (Order #9)
Value objectdefined only by its values, immutable (Money, Address)
Aggregatecluster of objects treated as one consistency boundary, accessed via its root (Order with its lines)
Repositorycollection-like access to aggregates
Domain serviceoperation that doesn't belong to one entity (TransferService)
Domain eventsomething meaningful that happened (OrderPlaced)
Bounded contexta boundary within which a model is consistent (Billing's "Customer" ≠ Support's "Customer")
Ubiquitous languageshared vocabulary between developers and domain experts

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.