Design Principles: KISS, DRY, YAGNI and SOLID
In a low-level design interview, nobody asks you to recite SOLID. But almost every follow-up question is secretly about it. "How would you add a new vehicle type?" is asking whether your design is open to extension. "How would you test this without sending real emails?" is asking whether your classes depend on abstractions. "Why does this class have twelve methods?" is asking about single responsibility.
Design principles are short rules of thumb for keeping code easy to change. They are not laws. Each one fixes a specific kind of pain, and each one, applied too eagerly, creates a different kind of pain. This post walks through the principles that matter most in LLD interviews. For each one you get the idea in plain words, a small Bad/Good code pair from a realistic design problem, what the bad version costs you, and when to leave the principle alone.
💡 How to use this in an interview: name a principle only when it explains a choice you are making. "I'll put the fee rules behind an interface so a new rate doesn't touch
ParkingLot; that's open/closed" lands well. Listing all five SOLID letters up front does not.
KISS: Keep It Simple
KISS ("keep it simple, stupid") says: pick the simplest design that meets the requirements you actually have. Simple means fewer moving parts, fewer classes to read, and code a teammate understands on the first pass. It does not mean sloppy. A simple design still has clear names and handles its edge cases.
The most common KISS violation in interviews is reaching for patterns before the problem asks for them. Here is a parking fee calculator for a lot with one rule: $3 per started hour, capped at $20 per day.
Bad:
class FeeRule(ABC):
@abstractmethod
def apply(self, minutes: int, fee: float) -> float: ...
class HourlyRule(FeeRule):
def apply(self, minutes: int, fee: float) -> float:
return fee + 3 * math.ceil(minutes / 60)
class DailyCapRule(FeeRule):
def apply(self, minutes: int, fee: float) -> float:
return min(fee, 20.0)
class FeeRuleChainFactory:
def build(self) -> list[FeeRule]:
return [HourlyRule(), DailyCapRule()]
class FeeCalculator:
def __init__(self, factory: FeeRuleChainFactory) -> None:
self.rules = factory.build()
def fee(self, minutes: int) -> float:
total = 0.0
for rule in self.rules:
total = rule.apply(minutes, total)
return total
What the bad version costs you. Five classes for two lines of arithmetic. A reader has to open every class to learn the rule, the order of the rules matters but is hidden in a factory, and in an interview you have spent ten minutes on something the interviewer considers trivial.
Good:
HOURLY_RATE = 3.0
DAILY_CAP = 20.0
def parking_fee(minutes: int) -> float:
hours = math.ceil(minutes / 60)
return min(hours * HOURLY_RATE, DAILY_CAP)
The whole rule fits on one screen, the constants have names, and it is trivially testable.
When not to apply it. KISS is about the requirements you have, so it stops being an argument once the
requirements grow. If the interviewer says "cars, motorcycles and trucks pay different rates, and weekends are
cheaper," a single function full of if statements is no longer simple; it is just short. That is the moment to
introduce a pricing interface (see the Strategy Pattern). KISS also never
excuses skipping input validation or thread safety the requirements call for. Simple means "no extra parts," not
"missing parts."
DRY: Don't Repeat Yourself
DRY says every piece of knowledge should live in one place. The key word is knowledge, not text. If the rule "a withdrawal may not exceed the daily limit" is written out in three methods, changing the limit means finding all three, and the day someone forgets one, the system enforces two different rules.
Here is a bank account where the same rule is copied into every way of taking money out.
Bad:
class Account:
def withdraw(self, amount: int) -> None:
if amount <= 0 or amount > self.balance:
raise ValueError("invalid amount")
if self.withdrawn_today + amount > 1_000:
raise ValueError("daily limit")
self.balance -= amount
self.withdrawn_today += amount
def transfer(self, to: "Account", amount: int) -> None:
if amount <= 0 or amount > self.balance:
raise ValueError("invalid amount")
if self.withdrawn_today + amount > 500: # someone changed only this one
raise ValueError("daily limit")
self.balance -= amount
self.withdrawn_today += amount
to.balance += amount
What the bad version costs you. The limits have already drifted apart (1,000 versus 500), and nobody can tell which one is the intended rule. Every new way to move money (bill pay, card purchase) copies the block again.
Good:
class Account:
DAILY_LIMIT = 1_000
def _debit(self, amount: int) -> None:
if amount <= 0 or amount > self.balance:
raise ValueError("invalid amount")
if self.withdrawn_today + amount > self.DAILY_LIMIT:
raise ValueError("daily limit")
self.balance -= amount
self.withdrawn_today += amount
def withdraw(self, amount: int) -> None:
self._debit(amount)
def transfer(self, to: "Account", amount: int) -> None:
self._debit(amount)
to.balance += amount
The rule lives in _debit and nowhere else. A new money-moving method gets the rule for free.
When not to apply it. Two pieces of code that look the same but represent different rules should stay
separate. Suppose a parking lot charges $3 per hour and, by coincidence, a car wash in the same building also
charges $3 per wash. Merging them into one PRICE = 3 constant couples two businesses that will change for
different reasons. The test is: "If one changes, must the other change too?" If not, the duplication is
accidental, and removing it creates a false dependency. A related trap is the "helper" with five boolean flags
that tries to serve every caller. Two or three plainly repeated lines are cheaper than one function nobody can
read.
YAGNI: You Aren't Gonna Need It
YAGNI says don't build features or extension points until a real requirement needs them. Every speculative hook costs code to write, read, test and keep working, and most of them are never used. Worse, when the real requirement finally arrives, it rarely has the shape you guessed.
A library system needs members to borrow and return books. The bad version prepares for a future nobody asked for.
Bad:
class Library:
def __init__(self) -> None:
self.plugins: list[LibraryPlugin] = []
self.event_bus = EventBus()
self.storage: StorageBackend = InMemoryStorage() # "we may move to SQL later"
self.currency_converter = CurrencyConverter() # "fines may go international"
def borrow(self, member_id: str, book_id: str, locale: str = "en-US") -> Loan:
for plugin in self.plugins:
plugin.before_borrow(member_id, book_id)
...
What the bad version costs you. You spend interview time wiring a plugin system, an event bus and a currency
converter that no requirement mentions, and you have less time for the parts that are graded: the loan rules,
holds and fines. Each extra parameter (locale) also has to be explained and tested.
Good:
class Library:
def __init__(self) -> None:
self.books: dict[str, Book] = {}
self.loans: dict[str, Loan] = {} # book_id -> active loan
def borrow(self, member_id: str, book_id: str, today: date) -> Loan:
if book_id in self.loans:
raise ValueError("book is already on loan")
loan = Loan(member_id, book_id, due=today + timedelta(days=14))
self.loans[book_id] = loan
return loan
When not to apply it. YAGNI is about speculative features, not about the extension points the interviewer has hinted at. If the prompt says "we'll add more payment methods later" or the follow-ups are predictable ("how would you add a new piece type?"), a small interface now is cheap and expected. YAGNI also doesn't apply to things that are expensive to retrofit: thread safety in a booking system, idempotency in a payment API, or keeping money as integer cents. Leave out features, not correctness.
⚠️ Common mistake: treating KISS and YAGNI as permission to write one giant class. They argue against unneeded structure. A
ParkingLotthat also parses input, formats receipts and stores tickets in a global dict is not simple; it is tangled. The next principle is the fix.
Separation of Concerns
Separation of concerns says different jobs belong in different places. A "concern" is a reason the code exists: business rules, storage, user input, formatting, talking to the network. When those are mixed in one method, you can't change one without reading and risking the others.
Here is an online store's checkout that does everything at once.
Bad:
def checkout(cart_json: str) -> str:
cart = json.loads(cart_json)
total = sum(item["price"] * item["qty"] for item in cart["items"])
if cart.get("coupon") == "SAVE10":
total = int(total * 0.9)
conn = sqlite3.connect("shop.db")
conn.execute("INSERT INTO orders VALUES (?, ?)", (cart["user"], total))
conn.commit()
smtplib.SMTP("mail.local").sendmail("[email protected]", cart["email"], f"Total: {total}")
return f"<p>Thanks! You paid ${total / 100:.2f}</p>"
What the bad version costs you. You cannot test the pricing rule without a database and a mail server. A change to the receipt HTML means editing the same function that holds the coupon logic. And a second entry point (a mobile API that sends different JSON) has to copy the pricing.
Good:
class PricingService:
def total(self, items: list[LineItem], coupon: str | None) -> int:
subtotal = sum(i.price_cents * i.qty for i in items)
return int(subtotal * 0.9) if coupon == "SAVE10" else subtotal
class CheckoutService:
def __init__(self, pricing: PricingService, orders: OrderRepository, mailer: Mailer) -> None:
self.pricing, self.orders, self.mailer = pricing, orders, mailer
def checkout(self, cart: Cart) -> Order:
order = Order(cart.user_id, self.pricing.total(cart.items, cart.coupon))
self.orders.save(order)
self.mailer.send_receipt(cart.email, order)
return order
Parsing JSON and rendering HTML now live at the edges (the API handler), pricing is a pure function you can test
in one line, and CheckoutService only orchestrates.
When not to apply it. Don't split by layer when there is nothing in the layer. A tic-tac-toe game does not need
a BoardRepository, a MoveService and a MoveController; one Game class with a Board is right. In an
interview, separate the concerns the problem actually has (rules versus storage versus I/O), and say out loud
that the rest would be a thin wrapper.
SOLID
SOLID is five principles for object-oriented design. They overlap with each other and with the ones above, but each gives you a precise name for a precise problem.
S: Single Responsibility Principle
The single responsibility principle (SRP) says a class should have one reason to change. "Reason to change" usually means "one group of people who would ask for the change." The finance team changes how invoices are calculated; the design team changes how they look; the ops team changes where they are stored.
Bad:
class Invoice:
def __init__(self, order: Order) -> None:
self.order = order
def total_cents(self) -> int:
return sum(line.price_cents * line.qty for line in self.order.lines)
def to_pdf(self) -> bytes: ... # layout, fonts, logo
def save(self, path: str) -> None: ... # file system
def email(self, to: str) -> None: ... # SMTP
What the bad version costs you. A font change and a tax change edit the same file, so they conflict in review
and can break each other. Testing total_cents means constructing a class that also knows about PDFs and SMTP.
Good:
class Invoice: # what the customer owes
def __init__(self, order: Order) -> None:
self.order = order
def total_cents(self) -> int:
return sum(line.price_cents * line.qty for line in self.order.lines)
class InvoicePdfRenderer: # how it looks
def render(self, invoice: Invoice) -> bytes: ...
class InvoiceSender: # how it gets to the customer
def __init__(self, mailer: Mailer) -> None:
self.mailer = mailer
def send(self, invoice: Invoice, to: str) -> None: ...
When not to apply it. SRP taken to the extreme gives you one class per method and a design nobody can follow.
A ParkingSpot with is_free(), assign() and release() has one responsibility (the state of one spot), even
though it has three methods. If two methods always change together, they belong together.
O: Open/Closed Principle
The open/closed principle (OCP) says a class should be open for extension but closed for modification: you
add new behavior by adding new code, not by editing code that already works. In practice it targets one smell, the
if/elif chain on a type that grows every time a new type appears.
Bad:
class DiscountCalculator:
def discount(self, cart: Cart, kind: str) -> int:
if kind == "percent":
return cart.subtotal * 10 // 100
elif kind == "flat":
return min(500, cart.subtotal)
elif kind == "bogo":
return sum(i.price_cents for i in cart.items if i.qty >= 2)
raise ValueError(kind)
What the bad version costs you. Every new promotion edits this method, re-tests every branch, and risks breaking the old ones. When the promotions team adds "free shipping over $50" next week, the method gets longer again.
Good:
class Discount(ABC):
@abstractmethod
def amount(self, cart: Cart) -> int: ...
class PercentOff(Discount):
def __init__(self, percent: int) -> None:
self.percent = percent
def amount(self, cart: Cart) -> int:
return cart.subtotal * self.percent // 100
class FlatOff(Discount):
def __init__(self, cents: int) -> None:
self.cents = cents
def amount(self, cart: Cart) -> int:
return min(self.cents, cart.subtotal)
A new promotion is a new class; the cart and the existing discounts don't change. This is the Strategy pattern, covered in depth in the Strategy Pattern post.
When not to apply it. If the variants differ only in numbers, use data, not classes: a dict of
{"car": 300, "truck": 600} hourly rates is open for extension without any interface at all. And if there are two
cases that will never grow (a door is open or closed), an if is clearer than a class hierarchy.
L: Liskov Substitution Principle
The Liskov substitution principle (LSP) says a subclass must work anywhere its parent works. Code written against the parent should never need to ask "which subclass is this?" A subclass that throws on a method its parent supports, or demands more from its callers, breaks that promise.
Bad:
class Account:
def __init__(self, balance: int) -> None:
self.balance = balance
def withdraw(self, amount: int) -> None:
self.balance -= amount
class FixedDeposit(Account):
def withdraw(self, amount: int) -> None:
raise RuntimeError("fixed deposits are locked until maturity")
def pay_bill(account: Account, amount: int) -> None:
account.withdraw(amount) # crashes for a FixedDeposit
What the bad version costs you. Every caller of Account has to learn about FixedDeposit and add an
isinstance check, which is exactly the coupling inheritance was supposed to remove. The type system says the
call is fine; production says otherwise.
Good:
class Account:
def __init__(self, balance: int) -> None:
self.balance = balance
def deposit(self, amount: int) -> None:
self.balance += amount
class CheckingAccount(Account):
def withdraw(self, amount: int) -> None:
self.balance -= amount
class FixedDeposit(Account):
def __init__(self, balance: int, matures_on: date) -> None:
super().__init__(balance)
self.matures_on = matures_on
def pay_bill(account: CheckingAccount, amount: int) -> None:
account.withdraw(amount) # only accounts that can withdraw get here
The hierarchy now says what is true: every account takes deposits, only some allow withdrawals.
When not to apply it. LSP is about inheritance, so the cheapest fix is often to not inherit. If you find
yourself bending a hierarchy to satisfy LSP, consider composition instead: a FixedDeposit could have a
Balance rather than be an Account. Don't build a deep tree of abstract classes just to model every
capability; that is the next principle's job.
I: Interface Segregation Principle
The interface segregation principle (ISP) says clients should not be forced to depend on methods they don't use. Prefer several small interfaces to one large one.
Bad:
class SmartDevice(ABC):
@abstractmethod
def turn_on(self) -> None: ...
@abstractmethod
def set_brightness(self, level: int) -> None: ...
@abstractmethod
def set_temperature(self, celsius: float) -> None: ...
@abstractmethod
def lock(self) -> None: ...
class SmartLock(SmartDevice):
def turn_on(self) -> None: pass
def set_brightness(self, level: int) -> None: raise NotImplementedError
def set_temperature(self, celsius: float) -> None: raise NotImplementedError
def lock(self) -> None: self.locked = True
What the bad version costs you. Every device implements methods that make no sense for it, usually by
throwing, which is an LSP violation waiting to happen. Adding set_fan_speed to the interface forces a change in
every device class, including the lock.
Good:
class Switchable(Protocol):
def turn_on(self) -> None: ...
def turn_off(self) -> None: ...
class Dimmable(Protocol):
def set_brightness(self, level: int) -> None: ...
class Lockable(Protocol):
def lock(self) -> None: ...
def unlock(self) -> None: ...
class SmartBulb: # Switchable and Dimmable
def turn_on(self) -> None: self.on = True
def turn_off(self) -> None: self.on = False
def set_brightness(self, level: int) -> None: self.level = level
class SmartLock: # Lockable only
def lock(self) -> None: self.locked = True
def unlock(self) -> None: self.locked = False
A "dim all lights" feature asks for list[Dimmable] and never sees a lock.
When not to apply it. One-method interfaces for everything make a design hard to navigate. If every
implementation genuinely supports all the methods (every PaymentMethod can charge and refund), keep them in
one interface. Split only when you see implementations stubbing methods out.
D: Dependency Inversion Principle
The dependency inversion principle (DIP) says high-level code (business rules) should depend on abstractions, not on concrete low-level details (a specific database, email provider or clock). The concrete pieces are passed in from outside, which is called dependency injection.
Bad:
class OrderNotifier:
def __init__(self) -> None:
self.client = SendGridClient(api_key=os.environ["SENDGRID_KEY"])
def order_shipped(self, order: Order) -> None:
self.client.send(order.email, f"Order {order.id} has shipped")
What the bad version costs you. Every unit test sends a real email (or fails without an API key). Switching providers, or adding SMS, means editing the notifier itself. The business rule ("tell the customer when an order ships") is welded to one vendor.
Good:
class MessageSender(Protocol):
def send(self, to: str, body: str) -> None: ...
class OrderNotifier:
def __init__(self, sender: MessageSender) -> None:
self.sender = sender
def order_shipped(self, order: Order) -> None:
self.sender.send(order.email, f"Order {order.id} has shipped")
class FakeSender: # in tests
def __init__(self) -> None:
self.sent: list[tuple[str, str]] = []
def send(self, to: str, body: str) -> None:
self.sent.append((to, body))
Production wires in OrderNotifier(SendGridSender(key)); tests wire in FakeSender() and assert on sent.
When not to apply it. You don't need an interface in front of every class. Value objects (Money, Ticket),
data containers and stable standard-library types (dict, datetime) are fine to use directly. Invert the
dependencies that touch the outside world (storage, network, time, randomness) or that the interviewer expects to
vary. Injecting a ListFactory to avoid writing [] is over-engineering.
💡 Interview tip: whenever your design reads the current time or a random number, take it as an argument or an injected clock. It makes your code testable, and it is the easiest way to show you understand DIP without saying the word.
Law of Demeter
The Law of Demeter, also called "talk to friends, not strangers," says a method should only call methods on
objects it directly holds: its own fields, its parameters, and objects it creates. Long chains like
a.b().c().d() reach through other objects' insides.
Bad:
class RideService:
def charge_rider(self, trip: Trip) -> None:
wallet = trip.rider.account.wallet
if wallet.balance_cents < trip.fare_cents:
raise ValueError("insufficient funds")
wallet.balance_cents -= trip.fare_cents
What the bad version costs you. RideService now depends on the shape of Rider, Account and Wallet.
If riders can pay by card, or wallets move to a separate payment service, this code breaks even though "charge
the rider" did not change. The balance check also lives outside the wallet, so another caller can skip it.
Good:
class Wallet:
def debit(self, cents: int) -> None:
if self.balance_cents < cents:
raise ValueError("insufficient funds")
self.balance_cents -= cents
class Rider:
def pay(self, cents: int) -> None:
self.account.wallet.debit(cents) # Rider knows its own parts
class RideService:
def charge_rider(self, trip: Trip) -> None:
trip.rider.pay(trip.fare_cents)
Each class talks to its neighbor and keeps its own rules. This is also called "tell, don't ask": tell the wallet to debit instead of asking for its balance and doing the math yourself.
When not to apply it. Chains through plain data are fine. order.shipping_address.zip_code on simple
dataclasses carries no behavior to hide, and wrapping it in order.shipping_zip() just adds a method. Fluent
builders (Query().where(...).limit(10)) also return the same object each time, so they don't reach into
strangers. Apply Demeter where the chain crosses objects that own rules.
When Principles Collide
The principles pull in different directions, and good design is choosing which one wins for this problem.
- DRY versus KISS. Removing duplication often adds an abstraction. If merging two 3-line blocks needs a function with flags, KISS wins and the duplication stays.
- YAGNI versus Open/Closed. OCP asks you to prepare for new types; YAGNI asks you not to prepare for things you don't need. Resolve it with evidence: build the extension point where the requirements or the interviewer's hints say change is coming, and nowhere else.
- SRP versus cohesion. Splitting a class gives each piece one job, but splitting too far scatters one idea across many files. Keep data and the rules that guard it together.
🎯 A good default: start with the simplest classes that meet the requirements. When a follow-up adds a variant, refactor toward the principle that absorbs it (usually OCP via an interface, or DIP via injection). Interviewers like seeing a design grow cleanly far more than seeing one built for every future on day one.
Design Principles in an Interview
You rarely get a question that says "explain SOLID." Instead, principles show up in three places.
While you design classes. As you introduce each class, say in one sentence what it is responsible for. If you
can't say it without "and," you probably have two classes. When you choose an interface over an if chain, name
the reason: "fees vary by vehicle type and the prompt says more types are coming."
In follow-ups. Most extensibility questions map to one principle. "Add a new payment method" tests OCP. "How would you test this?" tests DIP. "This class is getting big" tests SRP. If your design already absorbs the change in one new class, say so and show the class; that is the strongest answer you can give.
When you push back. Saying "I'd keep this as a dict of rates rather than a class per vehicle, because the types differ only in price" shows judgment. Interviewers at the senior level look for this as much as for clean abstractions: knowing when not to apply a principle is part of knowing it.
Here is what that sounds like in a parking lot interview, a few minutes into class design:
You: "Fees depend on the vehicle type and the prompt says hourly and daily rates are coming, so
ParkingLotwill hold aFeePolicyinterface instead of computing fees itself. Spot assignment is a single rule for now, nearest free spot, so I'll keep it as a method onLeveland pull it out if we need a second rule."
In two sentences you have applied OCP where change is expected, applied YAGNI where it isn't, and told the interviewer exactly where the design will bend when the follow-up comes.
A few smells to watch for in your own whiteboard code, and the principle each one points to:
| Smell | Principle | Usual fix |
|---|---|---|
if type == ... chain that grows with each new type |
Open/Closed | an interface with one class per type |
| A class name with "Manager" or "And" doing many jobs | Single Responsibility | split by reason to change |
A subclass that throws NotImplementedError |
Liskov / Interface Segregation | smaller interfaces, or composition |
datetime.now() or random() inside business logic |
Dependency Inversion | pass the time or an injected clock |
a.b.c.d.method() across objects with rules |
Law of Demeter | tell the nearest object what to do |
| The same rule copied in three methods | DRY | one private method that owns the rule |
| Classes no requirement mentions | YAGNI / KISS | delete them |
Summary
- KISS: the simplest design that meets today's requirements. Simple means no extra parts, not missing parts.
- DRY: one place per piece of knowledge. Don't merge code that only looks alike.
- YAGNI: no speculative features. Do build the extension points the prompt hints at, and never skip correctness.
- Separation of concerns: keep business rules apart from storage, I/O and formatting.
- SOLID: one reason to change per class (S); new behavior by new classes (O); subclasses that keep the parent's promises (L); small interfaces (I); business rules that depend on abstractions you inject (D).
- Law of Demeter: talk to the objects you hold; tell them what to do instead of reaching through them.
- Every principle has a cost. In an interview, apply the one that explains your choice, and say when you are choosing not to.