Design a Coffee Machine

0%

Editorial Solution

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Size Enum

Ingredient Class

Recipe as Data Object

Design Patterns

Strategy Pattern: Pluggable Recipes

Builder Pattern: Flexible Customization

Template Method: Brew Sequence

Define Class Members / Write Code

Ingredient

Recipe

CoffeeMachine with Thread Safety

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Brewing

ReadWriteLock for Higher Read Throughput

Dynamic Recipe Loading

Create/Explain Your Diagrams

Future Improvements

Table of Contents

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Size Enum

Ingredient Class

Recipe as Data Object

Design Patterns

Strategy Pattern: Pluggable Recipes

Builder Pattern: Flexible Customization

Template Method: Brew Sequence

Define Class Members / Write Code

Ingredient

Recipe

CoffeeMachine with Thread Safety

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Brewing

ReadWriteLock for Higher Read Throughput

Dynamic Recipe Loading

Create/Explain Your Diagrams

Future Improvements

A coffee machine sounds simple: press a button, get coffee. But underneath, the system must manage a recipe-driven brewing process, track multiple ingredient levels simultaneously, support drink customizations that adjust ingredient quantities, handle concurrent orders from multiple users, and ensure that ingredient availability checks and deductions happen atomically so the machine never oversells ingredients it does not have. The design challenge is building a flexible recipe system where adding a new drink requires zero code changes.

Interview Dialogue

CandidateWhich beverages should the machine support?
InterviewerClick to reveal answer
CandidateShould users be able to customize their drinks?
InterviewerClick to reveal answer
CandidateDo we need to handle concurrent orders from multiple users?
InterviewerClick to reveal answer
CandidateShould the machine track ingredient levels and support refills?
InterviewerClick to reveal answer
CandidateDo we need a payment system or a queue for orders?
InterviewerClick to reveal answer
Show all answers

Functional Requirements

  1. Brew Beverages from Recipes - The machine prepares beverages like Espresso, Latte, Cappuccino, and Hot Water. Each beverage follows a recipe specifying required ingredients and quantities.
  2. Track and Deduct Ingredients - The machine maintains inventory of ingredients (water, milk, coffee beans, sugar). Brewing deducts the required amounts atomically. The system rejects orders when any ingredient is insufficient.
  3. Customize Beverages - Users can customize drinks with extra shots, sugar levels, and size. Customizations adjust ingredient quantities accordingly.
  4. Refill and Status Display - An operator can refill ingredient containers to maximum capacity. The machine displays current ingredient levels and alerts when supplies run low.

Non-Functional Requirements

  • Thread Safety - Multiple users or automated systems may submit orders simultaneously. Ingredient availability checks and deductions must be atomic to prevent overselling.
  • Extensibility - Adding new beverages requires only a new Recipe definition. CoffeeMachine and Ingredient classes require no modification.

A customer walks up and taps "Large Latte, extra shot" on the screen. What does the machine need to do? It needs to look up how a Latte is made. That lookup target is a Recipe, a blueprint mapping ingredient names to quantities. The machine checks its containers: is there enough water, milk, and coffee beans? Each container is an Ingredient tracking its name, current quantity, and maximum capacity. The "large" size and "extra shot" are customizations that adjust quantities, and that adjustment logic lives in a BeverageBuilder. The machine orchestrates the whole flow: look up recipe, validate ingredients, deduct, and build the drink. That orchestrator is CoffeeMachine. The finished product handed to the customer is a Beverage. Not every noun in the requirements becomes a class. "Button" is a UI element rather than a domain object, but the nouns give you a strong starting lineup to refine.

The natural question is: why so many objects for a coffee machine? Because each one isolates a distinct concern. Changing the Latte recipe does not touch the Ingredient class. Adding a new ingredient does not touch the Recipe class. Let us walk through the full flow to see how they collaborate.

The machine has containers of Ingredient: water, milk, coffee beans, sugar. Each ingredient tracks its name, current quantity, and maximum capacity. An ingredient knows if it has enough for a given amount and provides methods for deduction and refill.

A Recipe defines what goes into a drink: Latte requires 100ml water, 150ml milk, 16g coffee beans. Different beverages have different recipes. The Recipe maps ingredient names to required quantities.

Why is Recipe a separate class? If ingredient requirements were hardcoded in CoffeeMachine, adding a new drink would mean editing the machine. Recipe externalizes the formula so the machine just reads it. This is the Strategy pattern: each Recipe is an interchangeable brewing strategy.

The customer wants a large size with an extra shot. A BeverageBuilder applies customizations: size multiplies all quantities (large = 2x), extra shots add more coffee beans. The builder accumulates customizations and produces a Beverage (the finished product with name, size, customizations, and cost).

The CoffeeMachine ties everything together: it holds the ingredient inventory and recipe registry, accepts orders, validates ingredients, deducts amounts, and returns the finished Beverage.

Key Insight

Why a dedicated Ingredient class instead of folding its responsibilities into Recipe? Separating them means Ingredient can change independently. When you add a new feature to Ingredient, you do not risk breaking Recipe logic.

Composition: CoffeeMachine owns Ingredients

The ingredient containers are physically inside the machine. They do not exist independently. If the machine is decommissioned, its water tank and bean hopper go with it. This is composition: the child's lifecycle is bound to the parent.

Composition: CoffeeMachine owns Recipes

The recipe registry is internal to this machine. Different machines might have different menus. The recipes are loaded when the machine starts and managed through its interface.

Strategy: Recipe as interchangeable brewing strategy

CoffeeMachine selects the appropriate Recipe based on the order and delegates ingredient calculations to it. The machine does not know Latte-specific or Espresso-specific formulas. It works with the Recipe abstraction.

Builder: BeverageBuilder creates Beverage

BeverageBuilder accumulates customizations (size, extra shots, sugar level) and creates the final Beverage object in its build() method. The Beverage is immutable after construction.

Association: Recipe references Ingredient names

Recipe maps ingredient names (strings) to quantities. It does not own or manage the Ingredient objects. The CoffeeMachine resolves ingredient names to Ingredient objects from its registry.

Key Insight

Why does BeverageBuilder produce an immutable Beverage? If the Beverage were mutable after creation, code could change the drink name or cost after the order is confirmed. Immutability guarantees the receipt matches what was brewed - no accidental or malicious modifications after the fact.

Size Enum

java
1public enum Size {
2  SMALL(1.0), MEDIUM(1.5), LARGE(2.0);
3
4  private final double multiplier;
5
6  Size(double multiplier) {
7    this.multiplier = multiplier;
8  }
9
10  public double getMultiplier() { return multiplier; }
11}

Each size carries a multiplier that scales all ingredient quantities. A large Latte uses 2x the milk, water, and coffee beans of a small.

Ingredient Class

Ingredient is not a hierarchy; it is a parameterized class. Water, milk, and coffee beans are all instances of Ingredient with different names and capacities. This avoids an unnecessary class hierarchy (WaterIngredient, MilkIngredient) when the behavior is identical.

Why not an Ingredient hierarchy? All ingredients behave the same way: they have a quantity that is deducted and refilled. Water does not have different deduction logic than milk. A flat Ingredient class with a name parameter is simpler and more flexible than a hierarchy.

Recipe as Data Object

Recipe is a data object mapping ingredient names to quantities. It is not an interface with subclasses (LatteRecipe, EspressoRecipe) because all recipes have the same structure. The difference between Latte and Espresso is data (which ingredients, how much), not behavior. Data differences belong in instances, not subclasses.

Key Insight

Why Recipe instances instead of LatteRecipe and EspressoRecipe subclasses? The difference between a Latte and an Espresso is data - which ingredients and how much - not behavior. All recipes follow the same structure: a map of ingredient names to quantities. Subclasses for data-only differences add classes without adding functionality.

Strategy Pattern: Pluggable Recipes

Each Recipe is an interchangeable brewing strategy. CoffeeMachine selects the appropriate recipe based on the order and delegates ingredient calculations to it. Without this pattern, CoffeeMachine would have if-else branches for each drink type, and adding a new drink would mean editing the machine.

Builder Pattern: Flexible Customization

The BeverageBuilder allows fluent construction:

java
1BeverageBuilder builder =
2new BeverageBuilder("Latte", 3.50)
3.setSize(Size.LARGE)
4.addExtraShots(1)
5.setSugarLevel(2);
6Beverage drink = machine.brew("Latte", builder);

Each method returns this, enabling chaining. The builder accumulates customizations and produces the final product in build(). This separates configuration from construction.

Template Method: Brew Sequence

The CoffeeMachine.brew() method follows a template: look up recipe, adjust for customizations, check all ingredients, deduct all ingredients, build beverage. Every brew follows this sequence regardless of the specific drink. If brew behavior needed to vary, subclasses could override specific steps.

Key Insight

The Strategy pattern is the core extensibility mechanism. Adding Pumpkin Spice Latte to the menu requires one Recipe definition: machine.addRecipe(new Recipe('Pumpkin Spice Latte', ingredients, 4.50)). Zero code changes to CoffeeMachine.

Interview Tip

In a live interview, show Recipe and Ingredient before CoffeeMachine.brew(). That makes the final brew method read like orchestration instead of magic: read recipe, validate all ingredients, deduct atomically, then build the beverage.

Ingredient

Ingredient is the lowest-level building block. It knows nothing about recipes, drinks, or the machine. It tracks one thing: how much of a substance is left. The natural question is how the machine decides how much of each ingredient to deduct. That responsibility belongs to Recipe.

Recipe

Recipe is pure data: a mapping from ingredient names to quantities. It does not call deduct() on anything. It does not check availability. It simply answers the question "what do you need and how much?" The caller (CoffeeMachine) uses this answer to validate and deduct. This separation is deliberate: Recipe never changes when the machine's ingredient-checking logic evolves.

CoffeeMachine with Thread Safety

Common Pitfall

Apply size and extra-shot customizations before the availability check, not after it. If you validate the base Latte recipe and only later add the extra shot, the machine can approve a drink it no longer has enough ingredients to brew correctly.

The brew() method checks all ingredients before deducting any. If the third ingredient is insufficient, the first two are not deducted. This all-or-nothing approach prevents partial deductions. Notice how CoffeeMachine ties the layers together: it reads the Recipe for requirements, asks each Ingredient if it has enough, then deducts from each Ingredient in sequence. No class reaches outside its boundary.

Run and Test

Browse the complete solution code and run it. Try modifying the code to experiment with the design.

Loading editor...

Single Responsibility Principle

  • CoffeeMachine orchestrates the brewing workflow. It does not know drink-specific formulas.
  • Recipe defines ingredient requirements for one beverage. It does not manage inventory.
  • Ingredient tracks its own quantity. It does not know about recipes or the machine.
  • BeverageBuilder handles customization. Beverage holds the final result.

Open/Closed Principle

  • Adding Mocha requires creating a new Recipe object and calling addRecipe(). CoffeeMachine, Ingredient, and Beverage require zero modification.
  • Adding a new ingredient (chocolate) requires creating a new Ingredient instance and calling addIngredient(). No code changes.
  • This is the most important SOLID principle for a coffee machine: the menu changes frequently.

Liskov Substitution Principle

  • If Ingredient were subclassed (PremiumIngredient with quality tracking), the subclass must honor hasSufficient() and deduct() contracts. CoffeeMachine calls these methods without knowing the concrete type.

Interface Segregation Principle

  • Recipe has focused methods: getAdjustedRequirements() and getBasePrice(). No class is forced to implement unrelated methods.

Dependency Inversion Principle

  • CoffeeMachine depends on Recipe (the abstraction), not on specific drink recipes. Recipes are injected via addRecipe(), not hardcoded.
Interview Tip

In interviews, demonstrate OCP by saying: 'To add a seasonal Pumpkin Spice Latte, I define one Recipe with ingredients and call addRecipe(). The CoffeeMachine class has not changed since we wrote it.'

Thread-Safe Brewing

The CoffeeMachine uses a ReentrantLock to serialize all brew and refill operations. The lock is acquired before checking ingredient availability and held through all deductions, ensuring the check-and-deduct sequence is atomic.

The race condition, step by step. Imagine milk has 200ml and two threads brew Lattes (each needing 150ml):

  1. Thread-A calls brew("Latte"), acquires nothing yet, reads milk: 200ml.
  2. Thread-B calls brew("Latte"), reads milk: 200ml (A has not deducted yet).
  3. Thread-A checks: 200 >= 150? Yes. Deducts 150. Milk is now 50ml.
  4. Thread-B checks: it saw 200 in step 2, decides 200 >= 150. Deducts 150. Milk is now -100ml.
  5. Thread-B's Latte is brewed with milk that does not physically exist.

With the ReentrantLock, step 2 blocks until step 3 completes. Thread-B then reads 50ml, fails the check, and rejects the order cleanly.

ReadWriteLock for Higher Read Throughput

For machines with digital displays showing ingredient levels, reads (getLowIngredients, getIngredientLevels) happen frequently while writes (brew, refill) happen less often. A ReadWriteLock would allow concurrent reads while only writes need exclusive access:

java
1// Read lock for status queries
2readLock.lock();
3try {
4  return ingredient.getCurrentQuantity();
5} finally {
6  readLock.unlock();
7}
8
9// Write lock for brew and refill
10writeLock.lock();
11try {
12  // check and deduct
13} finally {
14  writeLock.unlock();
15}

Dynamic Recipe Loading

Recipes can be loaded from a configuration file or database at startup. When the menu changes, the operator updates the configuration and the machine reloads recipes without firmware updates. The addRecipe() method is the extension point for this.

Level Expectations

Junior: explain the check-then-act race condition on ingredients.

Mid-level: design the lock strategy differentiating reads from writes.

Senior: discuss fleet management where a central server pushes recipe updates and ingredient alerts to hundreds of machines.

Key Insight

Why a ReadWriteLock instead of a simple mutex? A mutex blocks all concurrent access, even when multiple threads only want to read. A ReadWriteLock allows unlimited concurrent readers while still ensuring exclusive access for writers, dramatically improving throughput in read-heavy workloads.

Below is the class diagram for the coffee machine system.

Key points to highlight in an interview:

  • CoffeeMachine uses composition for both Ingredient and Recipe. Both are owned entities.
  • CoffeeMachine has a dashed dependency to Beverage (produces it) rather than composition (does not store it).
  • BeverageBuilder also has a dashed dependency to Beverage (creates it in build()).
  • There is no inheritance hierarchy for Recipe or Ingredient. Different drinks are different Recipe instances, not different classes.

Payment Integration

Add a PaymentProcessor interface supporting cash, card, and mobile payment. Beverage cost is calculated from recipe and customizations. Payment is validated before brewing starts, and the system refunds if brewing fails due to a mechanical error.

Scheduled Maintenance

Track total brew count and trigger cleaning reminders after a configurable number of brews. Monitor ingredient container freshness with expiration dates. Schedule periodic descaling based on water hardness and usage metrics.

Remote Monitoring and IoT

Report machine status, ingredient levels, and error codes to a cloud dashboard. Support remote recipe updates and configuration changes. Fleet management for operators managing multiple machines across locations.

Loyalty Program

A LoyaltyService tracks purchase history per user (identified by NFC card or app login). After every 10th purchase, the service issues a credit. The CoffeeMachine itself does not know about loyalty. The payment handler applies the discount transparently.

Nutritional Information

Each Ingredient carries nutritional data (calories, fat, protein per unit). Recipe computes total nutritional information based on ingredient quantities and size multiplier. The display shows calorie count before the customer confirms the order.

Try this problem yourself

Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.


Markdown supported

0%

Editorial Solution

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Size Enum

Ingredient Class

Recipe as Data Object

Design Patterns

Strategy Pattern: Pluggable Recipes

Builder Pattern: Flexible Customization

Template Method: Brew Sequence

Define Class Members / Write Code

Ingredient

Recipe

CoffeeMachine with Thread Safety

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Brewing

ReadWriteLock for Higher Read Throughput

Dynamic Recipe Loading

Create/Explain Your Diagrams

Future Improvements

Table of Contents

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Size Enum

Ingredient Class

Recipe as Data Object

Design Patterns

Strategy Pattern: Pluggable Recipes

Builder Pattern: Flexible Customization

Template Method: Brew Sequence

Define Class Members / Write Code

Ingredient

Recipe

CoffeeMachine with Thread Safety

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Brewing

ReadWriteLock for Higher Read Throughput

Dynamic Recipe Loading

Create/Explain Your Diagrams

Future Improvements