Interview conceptSoftware Engineering Fundamentals

Low-Level Object-Oriented Design And State Machines

Asked of: Software Engineer

Last updated

What's being tested

These problems test low-level object-oriented design: identifying domain objects, assigning responsibilities, preserving invariants, and exposing APIs that remain easy to extend. They also probe state-machine modeling, especially explicit transitions, guarded actions, timers, and exceptional overrides rather than scattered conditionals. General cares because billing, scheduling, games, and operational controls all require correctness, auditability, and maintainable business rules; a small modeling mistake can create incorrect charges, double bookings, or unsafe state transitions.

Core knowledge

  • Responsibility-driven design separates entities from services: Board owns placement and shots, Ship owns hit state, and a controller coordinates transitions without becoming a god object. Keep mutation near the invariant it protects.

  • A state machine consists of states, events, guards, and actions. Represent legal transitions explicitly, such as GREEN --timer--> YELLOW; reject invalid events instead of silently mutating state.

  • Use invariants as the design’s backbone: ships cannot overlap, bookings cannot overlap, exactly one traffic direction may be green, and a sunk ship has all segments hit. Validate invariants at mutation boundaries.

  • For intervals, use half-open ranges [start,end)[start, end); two bookings overlap exactly when a.start < b.end && b.start < a.end. This permits adjacent meetings and avoids ambiguous endpoint semantics.

  • Model value objects such as Money, TimeRange, Path, and Coordinate with validation, equality, and immutable fields. A Money object should prevent mixing currencies and avoid floating-point rounding errors.

  • For tiered billing, calculate each usage band’s contribution independently: charge=∑imax⁡(0,min⁡(u,upperi)−loweri)⋅ratei\text{charge}=\sum_i \max(0,\min(u,\text{upper}_i)-\text{lower}_i)\cdot\text{rate}_i. Define whether boundaries are inclusive and what happens beyond the final tier.

  • Prefer Strategy Pattern for replaceable policies such as file filters, pricing plans, or recurrence rules. A filter interface like matches(file) makes AND composition explicit and prevents a growing conditional chain.

  • Use Composite Pattern for directory trees: both files and directories expose a common searchable structure, while recursive traversal returns matching files. Sort results at the API boundary for deterministic behavior.

  • Separate commands from queries: book, cancel, shoot, and advanceTime mutate state; availability, find, and status observe it. This makes tests clearer and prevents read methods from unexpectedly changing state.

  • Treat time as a dependency through a clock abstraction or explicit advanceTime(now) input. Never rely on wall-clock calls inside transition logic; deterministic time is essential for testing phase boundaries and recurring schedules.

  • For recurring bookings, expand occurrences over the requested horizon, validate all conflicts first, then commit atomically. This gives all-or-nothing behavior: a recurrence cannot partially reserve a room after one occurrence conflicts.

  • Define idempotency for repeated commands. A repeated shot should return a stable result without damaging counts; repeated cancellation should have a documented outcome such as ALREADY_CANCELLED or a no-op.

Worked example

For “Design a four-way traffic signal controller with timed phases and emergency overrides”, I would first clarify whether the controller is a simulation or real-time component, whether timings are fixed, whether north-south and east-west are paired, and what emergency behavior means for active vehicles. I would declare a deterministic simulation assumption: advanceTime(delta) drives transitions, normal operation alternates paired directions, and emergency mode has explicit entry and exit semantics. I would organize the design around four pillars: immutable phase/value objects, a controller state machine, timer and transition handling, and safety invariants plus tests. A TrafficController would own the current mode and phase, while a Phase records direction, color, and remaining duration; transition logic would reject unsafe combinations such as two conflicting greens. I would model emergency override as a separate mode or guarded transition rather than a boolean checked throughout every method. The key tradeoff is whether emergency behavior immediately changes lights or first enters an all-red clearance phase: immediate response is faster, while clearance is safer and easier to specify. I would test exact-boundary advances, large time jumps, repeated emergency requests, and emergency exit into a known safe phase. If I had more time, I would add an event log and property-based tests asserting that conflicting directions are never simultaneously permissive.

A second angle

For “Design a meeting room scheduler with conflict detection and recurring weekly bookings”, the same state-and-invariant thinking applies, but the central challenge is temporal data rather than sequential phases. The scheduler’s states are closer to resource occupancy: a booking can be active or cancelled, and each occurrence must satisfy the interval invariant. The important design choice is whether recurring meetings are stored as rules or materialized occurrences; rules save space, while materialization simplifies conflict queries and cancellation. Clarify timezone, daylight-saving behavior, recurrence horizon, and whether cancellation affects one occurrence or the entire series. The API should validate the complete operation before mutating stored bookings.

Common pitfalls

Pitfall: Treating state as a collection of booleans, such as isGreen, isEmergency, and isYellow, permits impossible combinations. A better answer uses an explicit enum/state object and centralized transition rules with invariants.

Pitfall: Saying “I’ll create classes for everything” is not a design explanation. Name ownership and mutation boundaries: who validates overlap, who records hits, who calculates charges, and which object coordinates the workflow.

Pitfall: Hand-waving edge cases—exact timer boundaries, repeated shots, adjacent intervals, partial recurring-booking failure, currency rounding—signals shallow implementation depth. State the policy, encode it in one place, and describe a test for it.

Connections

The interviewer may pivot to SOLID principles, especially Single Responsibility and Open/Closed, or to design patterns such as Strategy, Composite, and State. They may also ask about immutability, dependency injection, property-based testing, serialization of state, or concurrency control when multiple callers mutate the same in-memory model.

Practice questions

Related concepts