Object-Oriented Domain Modeling And Extensibility
Asked of: Software Engineer
Last updated
What's being tested
These exercises test object-oriented domain modeling: translating nouns, rules, state transitions, and invariants into cohesive classes with explicit responsibilities. The interviewer is probing whether you can separate policy from mechanics, favor composition over brittle inheritance, and design interfaces that accommodate new stations, fare rules, ticket types, products, or payment methods without rewriting stable code. Amazon cares because maintainable services must evolve under changing requirements while preserving correctness, testability, and operational safety.
Core knowledge
-
Domain entities have identity and lifecycle; value objects are immutable and compared by value. Model
Station,Ticket, andOrderas entities, but represent money, coordinates, or fare amounts as validated value objects. -
Assign each class one primary reason to change using Single Responsibility Principle. A
FareCalculatorshould not load route data, process payments, mutate ticket inventory, and send notifications. -
Prefer composition over inheritance for variable business rules. Inject
FarePolicy,PricingStrategy,PaymentMethod, orCollisionResolverinterfaces so adding weekend caps or new payment providers does not modify a large conditional. -
Use polymorphism when behavior varies by type; use a data-driven table when behavior is simple configuration. A strategy hierarchy is justified for materially different algorithms, not merely because several classes share fields.
-
Make invariants explicit: adjacent stations must have a valid order, a ticket cannot be sold twice, a robot cannot occupy two charging stations, and a fare cannot become negative. Enforce them at the aggregate boundary rather than trusting callers.
-
Model lifecycle with a finite state machine when transitions matter:
Created → Paid → Fulfilled → Cancelled. Reject illegal transitions, make commands idempotent where retries are possible, and keep state changes atomic with their persistence. -
Define aggregate boundaries around consistency requirements. A ticket inventory aggregate can reserve one seat atomically, while catalog data and notification delivery can remain separate components connected through events.
-
For concurrent allocation, use a database constraint or conditional update such as
UPDATE ... WHERE status = 'AVAILABLE'; check affected rows. An in-memory lock works only within one process and fails across multiple service instances. -
Design retry-safe operations with an idempotency key scoped to the caller and operation. Persist the key with the result, return the original result on replay, and distinguish a duplicate request from a genuinely new purchase.
-
Separate domain policy from infrastructure through dependency inversion. The domain can depend on
StationRepositoryorPaymentGatewayinterfaces whilePostgres, HTTP clients, and clock implementations remain replaceable adapters. -
For a route with stations indexed from through , a unit-per-segment fare is . Dynamic insertion must define whether station identity, ordering, and existing ticket prices remain stable; otherwise historical calculations can silently change.
-
Test extensibility with contract and property tests: every
PaymentMethodmust preserve authorization/refund behavior, and fare properties such as symmetry, non-negativity, and a weekend cap must hold across generated routes and dates.
Worked example
For Design a Train Fare Calculator with Dynamic Stations and a Weekend Fare Cap, I would first clarify whether station order is linear, whether station names are unique, whether fares are based on current or purchase-time topology, and whether the weekend cap is per passenger, ticket, or account. I would state the assumptions: unique station IDs, ordered stations, one unit per adjacent segment, and a cap applied by a separate fare policy. I would organize the design around a Route aggregate, immutable station identity/order modeling, a FareCalculator, and composable FarePolicy implementations. Route would answer station-index or segment-distance queries, while the calculator would compute abs(indexA - indexB) and pass the base amount through policies. I would inject a Clock or date provider so weekday/weekend behavior is deterministic in tests. The explicit tradeoff is whether inserting a station changes historical fares: recalculating from current topology is simpler, while storing route version or purchase-time distance preserves transactional history. I would reject unknown stations, identical endpoints, duplicate station IDs, and negative or over-cap results at clear boundaries. If I had more time, I would add persistence-versioning, property-based tests, and concurrency rules for simultaneous station updates and fare reads.
A second angle
Design an extensible ticketing system applies the same modeling discipline, but correctness is dominated by concurrent ownership rather than route arithmetic. Start with ticket states such as Available, Held, Sold, and Expired, then define legal transitions and hold expiration explicitly. Use a conditional database write or serializable transaction to prevent two buyers from claiming one ticket, plus an idempotency record for retried purchase requests. The extension points are ticket categories, pricing rules, payment providers, and delivery channels, each behind narrow interfaces. The key framing shift is that aggregate boundaries and atomic persistence matter more than a rich inheritance tree.
Common pitfalls
Pitfall: Treating every noun as a class produces an anemic model full of getters and service-layer conditionals. Put invariants and state-changing behavior with the object that owns the data, while keeping orchestration services thin.
A tempting answer is “use an abstract Product base class and add subclasses for every future type.” That couples unrelated variation dimensions; explain which behavior varies, then use composition such as PricingStrategy, TaxPolicy, and PaymentMethod where those dimensions can change independently.
Pitfall: Saying “we can add a lock” without specifying its scope, lifetime, and failure behavior is not a concurrency design. Explain the authoritative store, atomic operation, transaction boundary, timeout, and retry semantics.
Candidates also sometimes over-engineer immediately with factories, event buses, repositories, and ten interfaces before clarifying requirements. Introduce abstractions at genuine change boundaries, name the simpler initial design, and identify the first requirement that would justify each extension point.
Connections
An interviewer may pivot to SOLID principles, design patterns such as Strategy, State, Factory, and Adapter, or domain-driven design concepts including aggregates and bounded contexts. They may also test transaction isolation, optimistic locking, idempotency, contract testing, and event-driven integration.
Further reading
-
Domain-Driven Design — Eric Evans — foundational treatment of entities, value objects, aggregates, and bounded contexts.
-
Design Patterns: Elements of Reusable Object-Oriented Software — Gamma et al. — precise catalog of Strategy, State, Factory, Adapter, and related patterns.
-
Effective Java — Joshua Bloch — practical guidance on immutability, interfaces, composition, and API design.
Practice questions
- Generalize Dictionary MergingAmazon · Software Engineer · Onsite · medium
- Design a Train Fare Calculator with Dynamic Stations and a Weekend Fare CapAmazon · Software Engineer · Onsite · medium
- Design a Parking Lot Management System's Object Model with Evolving RequirementsAmazon · Software Engineer · Other · medium
- Design an Extensible Cinema Ticket Pricing EngineAmazon · Software Engineer · Technical Screen · medium
- Model an Extensible Employee Cost CalculatorAmazon · Software Engineer · Onsite · medium
- Control Robot Charging with Repeated Polling and Exclusive Station AssignmentsAmazon · Software Engineer · Technical Screen · medium
- Design a pizza ordering systemAmazon · Software Engineer · Technical Screen · medium
- Design an extensible ticketing systemAmazon · Software Engineer · Technical Screen · hard
- Design a scalable parking lot systemAmazon · Software Engineer · Technical Screen · hard
Related concepts
- Object-Oriented Design Extensibility and SOLID
- Object-Oriented Design And Concurrency-Safe LLDSoftware Engineering Fundamentals
- Object-Oriented Design, API Design, And TestabilityCoding & Algorithms
- Object-Oriented Design For Service Code
- Stateful Data Structures And OOP API DesignCoding & Algorithms
- In-Memory Object-Oriented API DesignCoding & Algorithms