Common LLD Mistakes
Most failed LLD interviews don't fail on knowledge. The candidate knows what a strategy is, can recite SOLID and has solved the parking lot before. They fail on a handful of recurring design habits that interviewers spot within minutes: a class that does everything, objects that are just bags of setters, patterns used for their own sake, a double holding money.
This page covers ten of those habits. For each one you'll see what it looks like, why interviewers care, before and after code in Java plus Python or TypeScript, and a sentence you can say in the interview to show you've avoided it on purpose. The examples are kept small on purpose. Each "after" is the smallest change that fixes the problem, not a gold-plated rewrite.
| # | Mistake | One-line fix |
|---|---|---|
| 1 | God classes | Split by reason to change, and keep a thin coordinator |
| 2 | Anaemic domain models | Put rules on the object that owns the data |
| 3 | Over-patterning | Add a pattern when a requirement asks for it |
| 4 | Inheritance abuse | Compose capabilities, and inherit only for true substitutability |
| 5 | Primitive obsession | Small value objects for money, time ranges and identifiers |
| 6 | Ignoring concurrency | Make check-then-act atomic |
| 7 | Premature persistence and framework talk | Domain first, storage behind an interface |
| 8 | Leaky enums | Keep behaviour for each constant in one place |
| 9 | Untestable statics and singletons | Inject time, randomness and collaborators |
| 10 | Missing edge cases | Walk the boundaries before you code |
God classes
What it looks like. One class, often named after the system (ParkingSystem, LibraryManager, BookingEngine), holds the state and the allocation rules and the pricing and the payment calls and the printing. Every other class is a record with no behaviour, or doesn't exist.
Why it hurts. The class has many reasons to change, so every requirement edits it. It's hard to test one rule without setting up all the others, and bugs hide in the noise. In the example below, the freed spot is never returned to the pool. It's easy to miss in a 40-line method that does five things.
import java.util.*;
class ParkingSystem {
private final Map<String, String> spotByPlate = new HashMap<>();
private final Map<String, Long> entryByPlate = new HashMap<>();
private final List<String> freeSpots = new ArrayList<>(List.of("A1", "A2", "B1"));
String park(String plate, long nowMillis) {
if (freeSpots.isEmpty()) return null;
String spot = freeSpots.remove(0); // allocation
spotByPlate.put(plate, spot);
entryByPlate.put(plate, nowMillis);
System.out.println("Ticket: " + plate + " at " + spot); // presentation
return spot;
}
double exit(String plate, long nowMillis, String card) {
long hours = Math.max(1, (nowMillis - entryByPlate.remove(plate) + 3_599_999) / 3_600_000);
double fee = hours * 2.5; // pricing
if (!card.startsWith("4")) throw new RuntimeException("card declined"); // payment
spotByPlate.remove(plate); // the spot never goes back to freeSpots
System.out.printf("Charged %.2f%n", fee);
return fee;
}
}
class ParkingSystem:
def __init__(self):
self.spot_by_plate = {}
self.entry_by_plate = {}
self.free_spots = ["A1", "A2", "B1"]
def park(self, plate, now):
if not self.free_spots:
return None
spot = self.free_spots.pop(0) # allocation
self.spot_by_plate[plate] = spot
self.entry_by_plate[plate] = now
print(f"Ticket: {plate} at {spot}") # presentation
return spot
def exit(self, plate, now, card):
hours = max(1, -(-(now - self.entry_by_plate.pop(plate)) // 3600))
fee = hours * 2.5 # pricing
if not card.startswith("4"): # payment
raise RuntimeError("card declined")
del self.spot_by_plate[plate] # the spot never goes back
print(f"Charged {fee:.2f}")
return fee
The fix. Split by reason to change: allocation, pricing and payment each get their own home. A thin service coordinates them and returns data. Printing moves out to the caller.
import java.time.Duration;
import java.util.*;
final class SpotAllocator {
private final Deque<String> free;
SpotAllocator(Collection<String> spots) { free = new ArrayDeque<>(spots); }
Optional<String> take() { return Optional.ofNullable(free.pollFirst()); }
void release(String spot) { free.addLast(spot); }
}
final class HourlyPricing {
private final long centsPerHour;
HourlyPricing(long centsPerHour) { this.centsPerHour = centsPerHour; }
long feeCents(Duration stay) { return Math.max(1, (stay.toMinutes() + 59) / 60) * centsPerHour; }
}
interface PaymentGateway { void charge(String card, long cents); }
record Ticket(String plate, String spot, long entryMillis) {}
final class ParkingService {
private final SpotAllocator spots;
private final HourlyPricing pricing;
private final PaymentGateway payments;
private final Map<String, Ticket> active = new HashMap<>();
ParkingService(SpotAllocator spots, HourlyPricing pricing, PaymentGateway payments) {
this.spots = spots; this.pricing = pricing; this.payments = payments;
}
Ticket park(String plate, long nowMillis) {
String spot = spots.take().orElseThrow(() -> new IllegalStateException("lot is full"));
Ticket ticket = new Ticket(plate, spot, nowMillis);
active.put(plate, ticket);
return ticket;
}
long exit(String plate, long nowMillis, String card) {
Ticket ticket = active.get(plate);
if (ticket == null) throw new IllegalArgumentException("no active ticket for " + plate);
long fee = pricing.feeCents(Duration.ofMillis(nowMillis - ticket.entryMillis()));
payments.charge(card, fee); // if payment fails, the car is still recorded as parked
active.remove(plate);
spots.release(ticket.spot());
return fee;
}
}
from collections import deque
from dataclasses import dataclass
from typing import Protocol
class SpotAllocator:
def __init__(self, spots: list[str]) -> None:
self._free = deque(spots)
def take(self) -> str | None:
return self._free.popleft() if self._free else None
def release(self, spot: str) -> None:
self._free.append(spot)
class HourlyPricing:
def __init__(self, cents_per_hour: int) -> None:
self._rate = cents_per_hour
def fee_cents(self, stay_seconds: int) -> int:
return max(1, -(-stay_seconds // 3600)) * self._rate
class PaymentGateway(Protocol):
def charge(self, card: str, cents: int) -> None: ...
@dataclass(frozen=True)
class Ticket:
plate: str
spot: str
entry: int
class ParkingService:
def __init__(self, spots: SpotAllocator, pricing: HourlyPricing, payments: PaymentGateway) -> None:
self._spots, self._pricing, self._payments = spots, pricing, payments
self._active: dict[str, Ticket] = {}
def park(self, plate: str, now: int) -> Ticket:
spot = self._spots.take()
if spot is None:
raise RuntimeError("lot is full")
ticket = Ticket(plate, spot, now)
self._active[plate] = ticket
return ticket
def exit(self, plate: str, now: int, card: str) -> int:
ticket = self._active.get(plate)
if ticket is None:
raise KeyError(f"no active ticket for {plate}")
fee = self._pricing.fee_cents(now - ticket.entry)
self._payments.charge(card, fee)
del self._active[plate]
self._spots.release(ticket.spot)
return fee
The coordinator still exists, and that's fine. A service that orchestrates other objects isn't a god class. A service that implements every rule itself is. The test is: could you change pricing without opening ParkingService? In the "after" version, yes.
Say this: "I'm keeping
ParkingServiceas a coordinator. Allocation, pricing and payment each live in their own class, because they change for different reasons."
See Single Responsibility for the principle behind the split.
Anaemic domain models
What it looks like. Domain classes are just fields with getters and setters, and all the rules live in services that read a field, decide, and write it back. It's the opposite failure to the god class, and it often appears as a reaction to it.
Why it hurts. Nothing protects the invariant. Any code with a reference can call setBalance(-500). Rules get duplicated across services, and sooner or later one copy is wrong. Below, RefundJob subtracts instead of adding, and the model can't stop it.
class Wallet {
private long balanceCents;
public long getBalanceCents() { return balanceCents; }
public void setBalanceCents(long value) { balanceCents = value; }
}
class PaymentService {
void pay(Wallet wallet, long cents) {
if (wallet.getBalanceCents() < cents) throw new IllegalStateException("insufficient funds");
wallet.setBalanceCents(wallet.getBalanceCents() - cents);
}
}
class RefundJob {
void refund(Wallet wallet, long cents) {
wallet.setBalanceCents(wallet.getBalanceCents() - cents); // sign bug: nothing stops it
}
}
class Wallet {
balanceCents = 0; // public and mutable: anyone can write anything
}
class PaymentService {
pay(wallet: Wallet, cents: number): void {
if (wallet.balanceCents < cents) throw new Error("insufficient funds");
wallet.balanceCents -= cents;
}
}
class RefundJob {
refund(wallet: Wallet, cents: number): void {
wallet.balanceCents -= cents; // sign bug: nothing stops it
}
}
The fix. Give the object verbs that express the domain (credit, debit) and let it enforce its own rules. Remove the setter. Services still exist, but they ask the object to do things rather than doing them to it, which is the "tell, don't ask" idea from OOP fundamentals.
final class Wallet {
private long balanceCents;
long balanceCents() { return balanceCents; }
void credit(long cents) {
requirePositive(cents);
balanceCents += cents;
}
void debit(long cents) {
requirePositive(cents);
if (cents > balanceCents)
throw new IllegalStateException("insufficient funds: balance " + balanceCents + ", need " + cents);
balanceCents -= cents;
}
private static void requirePositive(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive, got " + cents);
}
}
class RefundJob {
void refund(Wallet wallet, long cents) { wallet.credit(cents); } // the verb makes the intent obvious
}
class Wallet {
#balanceCents = 0;
get balanceCents(): number { return this.#balanceCents; }
credit(cents: number): void {
Wallet.requirePositive(cents);
this.#balanceCents += cents;
}
debit(cents: number): void {
Wallet.requirePositive(cents);
if (cents > this.#balanceCents) {
throw new Error(`insufficient funds: balance ${this.#balanceCents}, need ${cents}`);
}
this.#balanceCents -= cents;
}
private static requirePositive(cents: number): void {
if (!Number.isInteger(cents) || cents <= 0) throw new Error(`amount must be a positive integer, got ${cents}`);
}
}
class RefundJob {
refund(wallet: Wallet, cents: number): void { wallet.credit(cents); }
}
Not every class needs behaviour. Pure data carriers such as DTOs, events and query results are fine as records. The mistake is making entities with invariants anaemic.
Say this: "
Walletowns the rule that its balance can't go negative, sodebitchecks it. There's no setter, so nothing else can break it."
Over-patterning
What it looks like. A design with a factory, a strategy, an abstract base class, a context object and a singleton, all to apply one 10% discount. It usually comes from a candidate who has studied patterns and wants to show it.
Why it hurts. Every indirection costs reading time, and an interviewer reading your code in a review will feel all of them. It also signals that you choose patterns from a list rather than from the forces in the problem. As the scoring page puts it, pattern-dropping is a red flag, not a bonus.
interface DiscountStrategy { long apply(long cents); }
abstract class AbstractDiscountStrategy implements DiscountStrategy {
protected abstract long percent();
public long apply(long cents) { return cents - cents * percent() / 100; }
}
final class TenPercentDiscount extends AbstractDiscountStrategy {
protected long percent() { return 10; }
}
final class DiscountStrategyFactory {
private static final DiscountStrategyFactory INSTANCE = new DiscountStrategyFactory();
static DiscountStrategyFactory getInstance() { return INSTANCE; }
DiscountStrategy create(String type) {
if (type.equals("TEN")) return new TenPercentDiscount();
throw new IllegalArgumentException(type);
}
}
final class DiscountContext {
private final DiscountStrategy strategy;
DiscountContext(DiscountStrategy strategy) { this.strategy = strategy; }
long execute(long cents) { return strategy.apply(cents); }
}
class Checkout {
long total(long cents) {
return new DiscountContext(DiscountStrategyFactory.getInstance().create("TEN")).execute(cents);
}
}
from abc import ABC, abstractmethod
class DiscountStrategy(ABC):
@abstractmethod
def apply(self, cents: int) -> int: ...
class AbstractPercentDiscount(DiscountStrategy):
@abstractmethod
def percent(self) -> int: ...
def apply(self, cents: int) -> int:
return cents - cents * self.percent() // 100
class TenPercentDiscount(AbstractPercentDiscount):
def percent(self) -> int:
return 10
class DiscountFactory:
_instance = None
@classmethod
def instance(cls):
cls._instance = cls._instance or cls()
return cls._instance
def create(self, kind: str) -> DiscountStrategy:
if kind == "TEN":
return TenPercentDiscount()
raise ValueError(kind)
class Checkout:
def total(self, cents: int) -> int:
return DiscountFactory.instance().create("TEN").apply(cents)
The fix. Write the simplest thing that meets today's requirement, and keep it in a shape that makes tomorrow's change easy. One parameter is enough here.
final class Checkout {
private final int discountPercent;
Checkout(int discountPercent) { this.discountPercent = discountPercent; }
long total(long cents) { return cents - cents * discountPercent / 100; }
}
class Checkout:
def __init__(self, discount_percent: int) -> None:
self._discount_percent = discount_percent
def total(self, cents: int) -> int:
return cents - cents * self._discount_percent // 100
When a second, differently shaped rule arrives ("buy two, get one free"), that's when a PricingRule interface earns its place. Then you introduce exactly one interface and two implementations, without a factory, an abstract base or a singleton. The upcoming pattern lessons in this course each have a "when not to use it" section, and the grouped design patterns overview has the same warnings.
Say this: "There's only one discount rule today, so it's a parameter. If we add rules with different shapes, I'd introduce a
PricingRuleinterface at that point. It's a two-minute change."
Inheritance abuse
What it looks like. Subclasses created to reuse fields or to add a capability: EvSpot extends ParkingSpot, AccessibleSpot extends ParkingSpot... and then someone needs an accessible spot with a charger. Java and TypeScript don't have multiple class inheritance, so the code gets copied into a fourth class. Each new capability doubles the number of classes.
Why it hurts. Inheritance is the tightest coupling there is. Subclasses depend on the parent's internals, combinations explode, and an "is-a" that's really a "has-a" eventually breaks Liskov substitution. The fragile base class problem is covered in OOP fundamentals.
class ParkingSpot {
final String id;
ParkingSpot(String id) { this.id = id; }
long hourlyRateCents() { return 200; }
boolean requiresPermit() { return false; }
}
class EvSpot extends ParkingSpot {
EvSpot(String id) { super(id); }
@Override long hourlyRateCents() { return 300; }
}
class AccessibleSpot extends ParkingSpot {
AccessibleSpot(String id) { super(id); }
@Override boolean requiresPermit() { return true; }
}
class AccessibleEvSpot extends EvSpot { // can't also extend AccessibleSpot, so copy its logic
AccessibleEvSpot(String id) { super(id); }
@Override boolean requiresPermit() { return true; }
}
class ParkingSpot {
constructor(readonly id: string) {}
hourlyRateCents(): number { return 200; }
requiresPermit(): boolean { return false; }
}
class EvSpot extends ParkingSpot {
override hourlyRateCents(): number { return 300; }
}
class AccessibleSpot extends ParkingSpot {
override requiresPermit(): boolean { return true; }
}
class AccessibleEvSpot extends EvSpot { // duplicates AccessibleSpot
override requiresPermit(): boolean { return true; }
}
The fix. Model capabilities as data the spot has, and put the rules that depend on them in one place. Matching a vehicle's needs becomes a set comparison, and adding a capability adds an enum constant, not a class hierarchy.
import java.util.*;
enum Feature { EV_CHARGER, ACCESSIBLE }
final class ParkingSpot {
private final String id;
private final Set<Feature> features;
ParkingSpot(String id, Set<Feature> features) {
this.id = id;
this.features = features.isEmpty() ? EnumSet.noneOf(Feature.class) : EnumSet.copyOf(features);
}
String id() { return id; }
boolean has(Feature f) { return features.contains(f); }
boolean satisfies(Set<Feature> needs) { return features.containsAll(needs); }
boolean requiresPermit() { return has(Feature.ACCESSIBLE); }
}
final class RateCard {
long hourlyRateCents(ParkingSpot spot) { return spot.has(Feature.EV_CHARGER) ? 300 : 200; }
}
enum Feature { EvCharger = "EV_CHARGER", Accessible = "ACCESSIBLE" }
class ParkingSpot {
private readonly features: ReadonlySet<Feature>;
constructor(readonly id: string, features: Iterable<Feature> = []) {
this.features = new Set(features);
}
has(f: Feature): boolean { return this.features.has(f); }
satisfies(needs: Iterable<Feature>): boolean { return [...needs].every((n) => this.features.has(n)); }
requiresPermit(): boolean { return this.has(Feature.Accessible); }
}
class RateCard {
hourlyRateCents(spot: ParkingSpot): number { return spot.has(Feature.EvCharger) ? 300 : 200; }
}
Inheritance is still right when subclasses are genuinely substitutable and differ in behaviour, not just data. Chess pieces with different move rules are the classic case. Ask: "Can I use the subclass everywhere the parent is expected, and does the subclass change how something works, not just what it holds?"
Say this: "EV and accessible are capabilities, not kinds of spot, so I'm composing them as a feature set. Otherwise every combination would need its own subclass."
Primitive obsession
What it looks like. Every concept is a String, long or double: book(String roomId, String email, long start, long end, double price). Swapping start and end compiles. An email without an @ gets in. Price is a float.
Why it hurts. Validation is scattered, or missing, at every call site. Argument order bugs are invisible to the compiler. Domain rules about the value (does this slot overlap that one?) have nowhere to live, so they get written again in every service.
import java.util.*;
class RoomBookingService {
private final List<long[]> bookings = new ArrayList<>(); // {start, end}, which unit? seconds? millis?
void book(String roomId, String email, long start, long end, double price) {
// no check that start < end, that email is valid, or that price is non-negative
for (long[] b : bookings) {
if (start < b[1] && b[0] < end) throw new IllegalStateException("overlap");
}
bookings.add(new long[] { start, end });
}
}
class RoomBookingService:
def __init__(self):
self.bookings = [] # list of (start, end) tuples, in what unit?
def book(self, room_id, email, start, end, price):
for s, e in self.bookings:
if start < e and s < end:
raise ValueError("overlap")
self.bookings.append((start, end))
The fix. Introduce small value objects that validate on construction and carry their own rules. Each one is a few lines, and they make the service read like the requirements. The upcoming Immutability, Value Objects and Defensive Copying lesson goes deeper. From Nouns to Classes covers entities vs value objects.
import java.time.Instant;
import java.util.*;
record Email(String value) {
Email {
if (!value.matches("[^@\\s]+@[^@\\s]+\\.[^@\\s]+")) throw new IllegalArgumentException("invalid email: " + value);
}
}
record Money(long cents, String currency) {
Money {
if (cents < 0) throw new IllegalArgumentException("money cannot be negative");
Objects.requireNonNull(currency);
}
}
record TimeSlot(Instant start, Instant end) {
TimeSlot {
if (!start.isBefore(end)) throw new IllegalArgumentException("slot must end after it starts");
}
boolean overlaps(TimeSlot other) { return start.isBefore(other.end) && other.start.isBefore(end); }
}
record RoomId(String value) {}
final class RoomBookingService {
private final Map<RoomId, List<TimeSlot>> booked = new HashMap<>();
void book(RoomId room, Email bookedBy, TimeSlot slot, Money price) {
List<TimeSlot> slots = booked.computeIfAbsent(room, r -> new ArrayList<>());
if (slots.stream().anyMatch(slot::overlaps)) throw new IllegalStateException("room already booked for " + slot);
slots.add(slot);
}
}
import re
from dataclasses import dataclass, field
from datetime import datetime
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self) -> None:
if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", self.value):
raise ValueError(f"invalid email: {self.value}")
@dataclass(frozen=True)
class Money:
cents: int
currency: str
def __post_init__(self) -> None:
if self.cents < 0:
raise ValueError("money cannot be negative")
@dataclass(frozen=True)
class TimeSlot:
start: datetime
end: datetime
def __post_init__(self) -> None:
if self.start >= self.end:
raise ValueError("slot must end after it starts")
def overlaps(self, other: "TimeSlot") -> bool:
return self.start < other.end and other.start < self.end
@dataclass
class RoomBookingService:
booked: dict[str, list[TimeSlot]] = field(default_factory=dict)
def book(self, room_id: str, booked_by: Email, slot: TimeSlot, price: Money) -> None:
slots = self.booked.setdefault(room_id, [])
if any(slot.overlaps(s) for s in slots):
raise ValueError(f"room already booked for {slot}")
slots.append(slot)
Don't wrap everything. A RoomId record is optional, since a string is fine for most identifiers in a 45-minute round. Money, time ranges and anything with validation rules are the ones worth wrapping.
Say this: "Money is a value object in cents, never a double.
TimeSlotvalidates itself and owns the overlap rule, so the booking service can't get it wrong."
Ignoring concurrency
What it looks like. A booking, allocation or inventory method that checks a condition and then acts on it, with nothing making the two steps atomic. It works in every single-threaded test and fails in production at the busiest moment.
Why it hurts. It's the classic check-then-act race. Two threads both see seat 7A as free, and both book it. In an interview, missing this in a booking or allocation problem is a significant gap at mid-level and above.
import java.util.*;
class SeatInventory {
private final Map<String, String> holderBySeat = new HashMap<>(); // not thread-safe either
boolean book(String seat, String user) {
if (holderBySeat.containsKey(seat)) return false; // check
holderBySeat.put(seat, user); // act: another thread can slip in between
return true;
}
}
class SeatInventory:
def __init__(self):
self._holder_by_seat = {}
def book(self, seat, user):
if seat in self._holder_by_seat: # check
return False
self._holder_by_seat[seat] = user # act: another thread can run in between
return True
The fix. Make the check and the act a single atomic step. For a single map entry, a concurrent map's putIfAbsent does exactly that. For anything touching several pieces of state (several seats, or seat plus payment hold), use one lock around the whole operation, or locks acquired in a fixed order.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
final class SeatInventory {
private final ConcurrentMap<String, String> holderBySeat = new ConcurrentHashMap<>();
/** Single seat: one atomic operation, no lock needed. */
boolean book(String seat, String user) {
return holderBySeat.putIfAbsent(seat, user) == null;
}
/** Several seats: all or nothing, so the whole check-and-act sits under one lock. */
synchronized boolean bookAll(List<String> seats, String user) {
if (seats.stream().anyMatch(holderBySeat::containsKey)) return false;
seats.forEach(s -> holderBySeat.put(s, user));
return true;
}
public static void main(String[] args) throws Exception {
SeatInventory inv = new SeatInventory();
ExecutorService pool = Executors.newFixedThreadPool(16);
AtomicInteger wins = new AtomicInteger();
List<Callable<Void>> tasks = new ArrayList<>();
for (int i = 0; i < 100; i++) {
String user = "u" + i;
tasks.add(() -> { if (inv.book("7A", user)) wins.incrementAndGet(); return null; });
}
pool.invokeAll(tasks);
pool.shutdown();
if (wins.get() != 1) throw new AssertionError("expected one winner, got " + wins.get());
System.out.println("one winner out of 100 attempts");
}
}
import threading
class SeatInventory:
def __init__(self) -> None:
self._holder_by_seat: dict[str, str] = {}
self._lock = threading.Lock()
def book_all(self, seats: list[str], user: str) -> bool:
with self._lock: # check and act happen together, or not at all
if any(s in self._holder_by_seat for s in seats):
return False
for s in seats:
self._holder_by_seat[s] = user
return True
if __name__ == "__main__":
inv = SeatInventory()
wins = []
threads = [threading.Thread(target=lambda u=f"u{i}": inv.book_all(["7A"], u) and wins.append(u))
for i in range(100)]
for t in threads:
t.start()
for t in threads:
t.join()
assert len(wins) == 1, wins
print("one winner out of 100 attempts")
Two misconceptions to avoid saying aloud. First, "I'll use a ConcurrentHashMap, so it's thread-safe." Each call is atomic, but containsKey followed by put still isn't. Second, "Python has the GIL, so it's fine." The GIL keeps the interpreter's internals consistent, but it can switch threads between your check and your act. The full treatment of locking choices is in race conditions and mutexes, semaphores and monitors.
Say this: "Booking is check-then-act on shared state, so it must be atomic. For one seat,
putIfAbsentdoes it. For several seats, I take one lock for the whole operation so it's all or nothing."
Premature persistence and framework talk
What it looks like. In minute three: "I'll use Spring Boot with JPA, a Postgres table for bookings with a composite index, and Redis for the seat locks." Or code where the domain logic is interleaved with SQL strings and connection handling.
Why it hurts. In an LLD round, the interviewer wants to see your object design, and framework choices tell them nothing about it. Storage code in the domain makes the logic untestable without a database and hides the rules among the plumbing. In a machine-coding round, framework setup eats the time you needed for features.
import java.sql.*;
class BookingService {
private final Connection conn;
BookingService(Connection conn) { this.conn = conn; }
boolean book(String seat, String user) throws SQLException {
try (PreparedStatement check = conn.prepareStatement("SELECT 1 FROM bookings WHERE seat = ?")) {
check.setString(1, seat);
if (check.executeQuery().next()) return false; // the business rule is buried in SQL plumbing
}
try (PreparedStatement insert = conn.prepareStatement("INSERT INTO bookings(seat, user_id) VALUES (?, ?)")) {
insert.setString(1, seat);
insert.setString(2, user);
insert.executeUpdate();
}
return true;
}
}
import sqlite3
class BookingService:
def __init__(self, db_path: str) -> None:
self.conn = sqlite3.connect(db_path)
self.conn.execute("CREATE TABLE IF NOT EXISTS bookings (seat TEXT PRIMARY KEY, user_id TEXT)")
def book(self, seat: str, user: str) -> bool:
if self.conn.execute("SELECT 1 FROM bookings WHERE seat = ?", (seat,)).fetchone():
return False
self.conn.execute("INSERT INTO bookings VALUES (?, ?)", (seat, user))
self.conn.commit()
return True
The fix. Design the domain and the service first, with storage behind a narrow interface. Implement it in memory. Then, if asked, explain how a database implementation would keep the same guarantees. That's the repository pattern, used for the reason it exists.
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
record Booking(String seat, String userId) {}
interface BookingRepository {
/** Stores the booking unless the seat is taken. Returns false if it was. Must be atomic. */
boolean addIfSeatFree(Booking booking);
Optional<Booking> findBySeat(String seat);
}
final class InMemoryBookingRepository implements BookingRepository {
private final Map<String, Booking> bySeat = new ConcurrentHashMap<>();
public boolean addIfSeatFree(Booking b) { return bySeat.putIfAbsent(b.seat(), b) == null; }
public Optional<Booking> findBySeat(String seat) { return Optional.ofNullable(bySeat.get(seat)); }
}
final class BookingService {
private final BookingRepository bookings;
BookingService(BookingRepository bookings) { this.bookings = bookings; }
boolean book(String seat, String user) {
return bookings.addIfSeatFree(new Booking(seat, user));
}
}
import threading
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class Booking:
seat: str
user_id: str
class BookingRepository(Protocol):
def add_if_seat_free(self, booking: Booking) -> bool: ... # must be atomic
class InMemoryBookingRepository:
def __init__(self) -> None:
self._by_seat: dict[str, Booking] = {}
self._lock = threading.Lock()
def add_if_seat_free(self, booking: Booking) -> bool:
with self._lock:
if booking.seat in self._by_seat:
return False
self._by_seat[booking.seat] = booking
return True
class BookingService:
def __init__(self, bookings: BookingRepository) -> None:
self._bookings = bookings
def book(self, seat: str, user: str) -> bool:
return self._bookings.add_if_seat_free(Booking(seat, user))
Notice the repository method is named for the guarantee (addIfSeatFree), not as a generic save. That's the hook for the database discussion. A database implementation keeps the same promise with a unique constraint on seat, and returns false on a constraint violation. The atomicity requirement belongs to the interface, so every implementation has to honour it.
Say this: "I'll keep storage in memory behind a repository. If we persist it later, a unique constraint on the seat gives the same atomic guarantee. The service doesn't change."
Leaky enums
What it looks like. An enum (VehicleType, PaymentMethod, OrderStatus) with switch statements about it spread across the codebase: one in the fee calculator, one in spot matching, one in the receipt printer. Adding a constant means finding every switch, and the one you miss falls into a default branch that silently does the wrong thing.
Why it hurts. The knowledge about each constant has leaked out of the enum into every client. It's an open/closed violation that hides in plain sight. A related leak is relying on ordinal() or the declaration order for logic, so reordering constants changes behaviour.
enum VehicleType { MOTORBIKE, CAR, VAN }
class Pricing {
long hourlyCents(VehicleType t) {
switch (t) {
case MOTORBIKE: return 100;
case CAR: return 200;
default: return 300; // a new BUS constant silently gets the van price
}
}
}
class SpotMatcher {
boolean fits(VehicleType vehicle, int spotSize) {
return vehicle.ordinal() <= spotSize; // breaks if anyone reorders the constants
}
}
enum VehicleType { Motorbike, Car, Van }
function hourlyCents(t: VehicleType): number {
switch (t) {
case VehicleType.Motorbike: return 100;
case VehicleType.Car: return 200;
default: return 300; // a new Bus silently gets the van price
}
}
function fits(vehicle: VehicleType, spotSize: number): boolean {
return vehicle <= spotSize; // numeric enum values leak into the logic
}
The fix. Keep each constant's data and behaviour in one place, and make the compiler tell you when a new constant is incomplete. In Java, give the enum fields and a constructor, so a constant can't be declared without them. In TypeScript, use a Record keyed by the union type, which fails to compile if a key is missing. If the per-type behaviour gets complex, switch to polymorphism, with one class per type behind an interface.
enum SpotSize { SMALL, MEDIUM, LARGE }
enum VehicleType {
MOTORBIKE(SpotSize.SMALL, 100),
CAR(SpotSize.MEDIUM, 200),
VAN(SpotSize.LARGE, 300);
// BUS(...) cannot be added without stating its size and rate
private final SpotSize minSpot;
private final long hourlyCents;
VehicleType(SpotSize minSpot, long hourlyCents) { this.minSpot = minSpot; this.hourlyCents = hourlyCents; }
long hourlyCents() { return hourlyCents; }
boolean fitsIn(SpotSize spot) { return spot.compareTo(minSpot) >= 0; }
}
type VehicleType = "MOTORBIKE" | "CAR" | "VAN";
type SpotSize = "SMALL" | "MEDIUM" | "LARGE";
const SPOT_RANK: Record<SpotSize, number> = { SMALL: 0, MEDIUM: 1, LARGE: 2 };
// Adding "BUS" to VehicleType makes this object fail to compile until BUS has rules.
const VEHICLE_RULES: Record<VehicleType, { minSpot: SpotSize; hourlyCents: number }> = {
MOTORBIKE: { minSpot: "SMALL", hourlyCents: 100 },
CAR: { minSpot: "MEDIUM", hourlyCents: 200 },
VAN: { minSpot: "LARGE", hourlyCents: 300 },
};
function hourlyCents(t: VehicleType): number {
return VEHICLE_RULES[t].hourlyCents;
}
function fitsIn(t: VehicleType, spot: SpotSize): boolean {
return SPOT_RANK[spot] >= SPOT_RANK[VEHICLE_RULES[t].minSpot];
}
Comparing SpotSize with compareTo in Java does rely on declaration order. That's acceptable inside the enum that defines the order, where it's documented and local. It's not acceptable in some other class that happens to know the order.
When to stop using an enum altogether is a judgement call that From Nouns to Classes discusses under "enums vs polymorphism". The short version: if the per-constant behaviour is a few values, keep the enum with fields. If it's an algorithm per constant, use classes.
Say this: "Each vehicle type's rate and minimum spot live on the enum, so adding a type is one line and the compiler forces me to fill in its rules."
Untestable statics and singletons
What it looks like. Business logic that reaches out to the world through static calls: System.currentTimeMillis(), new Random(), Config.getInstance(), EmailSender.send(...). The class looks self-contained, but it has hidden inputs you can't control in a test.
Why it hurts. To test "the token bucket refills after one second", you have to actually wait a second. To test "a snake sends you down", you have to retry until the dice cooperate. Singletons also carry state between tests, so they pass alone and fail together. The creational patterns page explains why Singleton is usually the wrong tool.
import java.util.*;
final class AppConfig {
private static final AppConfig INSTANCE = new AppConfig();
static AppConfig getInstance() { return INSTANCE; }
int requestsPerSecond() { return 5; }
}
class RateLimiter {
private final Map<String, Deque<Long>> recent = new HashMap<>();
boolean allow(String client) {
long now = System.currentTimeMillis(); // hidden input
int limit = AppConfig.getInstance().requestsPerSecond(); // hidden input
Deque<Long> times = recent.computeIfAbsent(client, c -> new ArrayDeque<>());
while (!times.isEmpty() && now - times.peekFirst() >= 1000) times.pollFirst();
if (times.size() >= limit) return false;
times.addLast(now);
return true;
}
}
import time
from collections import deque
CONFIG = {"requests_per_second": 5} # module-level global
class RateLimiter:
def __init__(self):
self.recent = {}
def allow(self, client):
now = time.monotonic() # hidden input
limit = CONFIG["requests_per_second"] # hidden input
times = self.recent.setdefault(client, deque())
while times and now - times[0] >= 1.0:
times.popleft()
if len(times) >= limit:
return False
times.append(now)
return True
The fix. Turn hidden inputs into constructor parameters. Time becomes a Clock (Java) or a now function (Python), and configuration becomes a plain value. Production wires the real ones once, in main, and tests pass controllable ones. This is dependency injection in its simplest form.
import java.time.*;
import java.util.*;
final class RateLimiter {
private final Map<String, Deque<Instant>> recent = new HashMap<>();
private final Clock clock;
private final int perSecond;
RateLimiter(Clock clock, int perSecond) { this.clock = clock; this.perSecond = perSecond; }
synchronized boolean allow(String client) {
Instant now = clock.instant();
Deque<Instant> times = recent.computeIfAbsent(client, c -> new ArrayDeque<>());
while (!times.isEmpty() && !times.peekFirst().plusSeconds(1).isAfter(now)) times.pollFirst();
if (times.size() >= perSecond) return false;
times.addLast(now);
return true;
}
}
class RateLimiterTest {
static final class TestClock extends Clock {
Instant now = Instant.parse("2026-01-01T00:00:00Z");
public ZoneId getZone() { return ZoneOffset.UTC; }
public Clock withZone(ZoneId zone) { return this; }
public Instant instant() { return now; }
}
public static void main(String[] args) {
TestClock clock = new TestClock();
RateLimiter limiter = new RateLimiter(clock, 2);
if (!limiter.allow("c") || !limiter.allow("c")) throw new AssertionError("first two allowed");
if (limiter.allow("c")) throw new AssertionError("third in the same second is rejected");
clock.now = clock.now.plusSeconds(1); // no sleeping: just move the clock
if (!limiter.allow("c")) throw new AssertionError("allowed again after one second");
System.out.println("rate limiter tests passed");
}
}
import time
from collections import deque
from typing import Callable
class RateLimiter:
def __init__(self, per_second: int, now: Callable[[], float] = time.monotonic) -> None:
self._per_second = per_second
self._now = now
self._recent: dict[str, deque[float]] = {}
def allow(self, client: str) -> bool:
now = self._now()
times = self._recent.setdefault(client, deque())
while times and now - times[0] >= 1.0:
times.popleft()
if len(times) >= self._per_second:
return False
times.append(now)
return True
if __name__ == "__main__":
t = [0.0]
limiter = RateLimiter(2, now=lambda: t[0])
assert limiter.allow("c") and limiter.allow("c")
assert not limiter.allow("c")
t[0] += 1.0 # no sleeping: just move the clock
assert limiter.allow("c")
print("rate limiter tests passed")
"Only one instance" is a wiring decision, not a class decision. Create one RateLimiter in main and pass it to whoever needs it, and you get a single instance without any of Singleton's costs. The same goes for random number generators in games. Inject a Dice or a seeded Random, as the Snake and Ladders case study needs to.
Say this: "Time is injected through a
Clock, so I can test the refill without sleeping. There's one limiter becausemaincreates one, not because the class enforces it."
Missing edge cases
What it looks like. Code that handles the example in the problem statement and nothing else. In interval problems (meeting rooms, hotel bookings, parking reservations), it's usually an overlap check that only catches some overlaps. In other problems, it's the empty list, the zero amount, the exact boundary or the duplicate request.
Why it hurts. The interviewer has a list of edge cases, and they'll try them. Each one you handle without being asked is a positive signal. Each one they find is a negative one.
import java.util.*;
class MeetingRoom {
private final List<int[]> bookings = new ArrayList<>(); // {startMinute, endMinute}
boolean book(int start, int end) {
for (int[] b : bookings) {
// only catches a new meeting that STARTS inside an existing one
if (start >= b[0] && start < b[1]) return false;
}
bookings.add(new int[] { start, end }); // even accepts end <= start
return true;
}
}
class MeetingRoom:
def __init__(self):
self.bookings = []
def book(self, start, end):
for s, e in self.bookings:
if s <= start < e: # misses meetings that start before and end inside, or cover it
return False
self.bookings.append((start, end))
return True
The fix. Use half-open intervals [start, end), which make back-to-back meetings legal without special cases. Two intervals overlap exactly when each starts before the other ends. Validate the input first. Then test each boundary explicitly.
import java.util.*;
final class MeetingRoom {
private final TreeMap<Integer, Integer> endByStart = new TreeMap<>(); // half-open [start, end)
synchronized boolean book(int start, int end) {
if (start < 0 || end > 24 * 60) throw new IllegalArgumentException("outside the day: " + start + "-" + end);
if (start >= end) throw new IllegalArgumentException("meeting must end after it starts");
Map.Entry<Integer, Integer> before = endByStart.floorEntry(start); // latest meeting starting at or before
Integer after = endByStart.ceilingKey(start); // earliest meeting starting at or after
if (before != null && before.getValue() > start) return false; // it hasn't ended when we start
if (after != null && after < end) return false; // it starts before we end
endByStart.put(start, end);
return true;
}
public static void main(String[] args) {
MeetingRoom room = new MeetingRoom();
check(room.book(600, 660), "10:00-11:00 on an empty room");
check(room.book(660, 720), "back-to-back 11:00-12:00 is allowed");
check(!room.book(630, 650), "inside an existing meeting");
check(!room.book(570, 610), "starts before, ends inside");
check(!room.book(540, 780), "covers existing meetings entirely");
check(!room.book(600, 660), "exact duplicate");
check(room.book(540, 600), "ends exactly when the next starts");
try { room.book(700, 700); check(false, "zero-length rejected"); }
catch (IllegalArgumentException e) { check(true, "zero-length meeting rejected"); }
System.out.println("all meeting-room edge cases pass");
}
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
}
import bisect
import threading
class MeetingRoom:
"""Bookings are half-open intervals [start, end) in minutes since midnight."""
def __init__(self) -> None:
self._starts: list[int] = []
self._ends: list[int] = []
self._lock = threading.Lock()
def book(self, start: int, end: int) -> bool:
if start < 0 or end > 24 * 60:
raise ValueError(f"outside the day: {start}-{end}")
if start >= end:
raise ValueError("meeting must end after it starts")
with self._lock:
i = bisect.bisect_right(self._starts, start)
if i > 0 and self._ends[i - 1] > start: # previous one still running
return False
if i < len(self._starts) and self._starts[i] < end: # next one starts too soon
return False
self._starts.insert(i, start)
self._ends.insert(i, end)
return True
if __name__ == "__main__":
room = MeetingRoom()
assert room.book(600, 660)
assert room.book(660, 720) # back to back
assert not room.book(630, 650) # inside
assert not room.book(570, 610) # starts before, ends inside
assert not room.book(540, 780) # covers
assert not room.book(600, 660) # duplicate
assert room.book(540, 600) # ends exactly when the next starts
try:
room.book(700, 700)
raise AssertionError("zero-length should fail")
except ValueError:
pass
print("all meeting-room edge cases pass")
The sorted structure isn't just faster (O(log n) per booking instead of O(n)). It also makes the reasoning local: only the two neighbouring meetings can conflict.
An edge-case checklist
Run through this list during the use-cases step. You won't need all of it for every problem, but you'll always need some of it.
| Category | Ask |
|---|---|
| Empty | No spots, no users, no items, an empty input line? |
| Boundaries | Exactly at the limit, exactly at the due time, back-to-back intervals? |
| Zero and negative | Zero amount, negative quantity, zero-length duration? |
| Duplicates | The same request twice, the same user listed twice, a re-entry without exit? |
| Missing references | An unknown id, a deleted item, an expired session? |
| Ordering | Return before borrow, exit before entry, settle before any expense? |
| Rounding | Indivisible amounts, partial hours, time-zone and day boundaries? |
| Concurrency | Two actors on the same object at the same moment? |
| Capacity | Full lot, sold-out show, a member at their loan limit? |
Say this: "I'm treating bookings as half-open intervals, so back-to-back is allowed. I'll check overlaps against the neighbours on both sides. And I'm validating that end is after start before anything else."
Spotting these in your own practice
After each practice problem, scan your code for these quick tells:
- A class with more than about seven public methods, or one that imports from every other package. That's a possible god class.
- Setters on entities, or services that read a field and write it back. That's a possible anaemic model.
- An interface with one implementation and no requirement asking for a second. That's possible over-patterning.
- A subclass that overrides nothing behavioural, or that exists only to set a flag. That's possible inheritance abuse.
doublenear money, orlong start, long endparameter pairs. That's primitive obsession.if (!map.containsKey(k)) map.put(k, v)on shared state. That's a check-then-act race.- SQL, HTTP or framework annotations in a domain class. That's premature persistence.
- The same
switchon an enum in more than one file. That's a leaky enum. now(),random()orgetInstance()inside business logic. That's an untestable hidden input.- No test or check for the boundary values from the clarification step. That's missing edge cases.
Then compare your code with how the mock parking-lot interview handles the same traps live.
Interview questions
- "Your
BookingServicehas a lot of methods. Is it a god class?" Count the reasons it changes, not its methods. If it only coordinates (it looks things up, calls domain objects in order and records results), many methods can be fine. If pricing, validation and notification rules are implemented inside it, split them out. - "Isn't putting logic in entities a violation of single responsibility?" No. An entity's responsibility is to keep its own state valid, and
debitrefusing to overdraw is that responsibility. What would violate SRP is the entity also sending emails or writing to a database. - "When is it right to add a pattern you don't need yet?" When the interviewer has told you the variation is coming, or the cost of adding it later is high (a public API boundary, for example). In a 45-minute round, almost everything else can wait.
- "Why not just make every method
synchronized?" It can still be wrong, because a sequence of synchronized calls isn't atomic. It also serialises unrelated work and risks deadlock if synchronized methods call each other across objects. Identify the invariant, then protect exactly the operation that maintains it. - "Should I ever mention databases in an LLD round?" Yes, when asked how the design would persist, or when atomicity depends on it. Explain how the repository's guarantee, such as "add if seat free", maps onto a constraint or a conditional update. Avoid leading with technology choices.
- "How do you test code that depends on the current time?" Inject the time source (a
Clockin Java, a function in Python or TypeScript), use the real one in production, and use a controllable one in tests. Never sleep in unit tests. - "Enum with a switch, or polymorphism?" If each constant differs by a few data values, put fields on the enum. If each constant has its own algorithm, or new constants arrive often, use an interface with one class per variant. A switch repeated in several places is the signal to move.