How do you approach an object-oriented design question in an interview when you have to think out loud?
The structure that works is clarify, model, then justify. Start by asking two or three questions about the requirements, because the constraints are what determine the design. Is the order total the same for every customer or does it depend on a tier? Will the storage change? How many orders are there? Each answer removes a design option, and asking them first shows the interviewer you are designing rather than reciting.
public class Main {
public static void main(String[] args) {
OrderRepository repo = new InMemoryOrderRepository();
OrderService service = new OrderService(repo, new FlatFee(5.0));
service.place("ada", new Line("Book", 20.0));
System.out.println(service.totalFor("ada"));
}
}
interface OrderRepository {
void save(String customer, double amount);
double total(String customer);
}
interface Fee {
double apply(double amount);
}
class FlatFee implements Fee {
private final double amount;
FlatFee(double amount) { this.amount = amount; }
public double apply(double value) { return value + amount; }
}
class InMemoryOrderRepository implements OrderRepository {
private final java.util.Map<String, Double> totals = new java.util.HashMap<>();
public void save(String customer, double amount) {
totals.put(customer, totals.getOrDefault(customer, 0.0) + amount);
}
public double total(String customer) { return totals.getOrDefault(customer, 0.0); }
}
class OrderService {
private final OrderRepository repo;
private final Fee fee;
OrderService(OrderRepository repo, Fee fee) { this.repo = repo; this.fee = fee; }
void place(String customer, Line line) { repo.save(customer, line.amount()); }
double totalFor(String customer) { return fee.apply(repo.total(customer)); }
}
class Line {
private final double amount;
Line(String product, double amount) { this.amount = amount; }
double amount() { return amount; }
}Then model the domain out loud, naming the classes as you go and saying what each one owns. The code shows the shape of a plausible answer. An order service depends on an order repository and on a fee policy, both as interfaces. The repository decides where orders are kept, the fee policy decides how the total is adjusted, and the service orchestrates the two. The output shows a total of 25.0 for a 20.0 order with a flat fee of 5.0.
The crucial part is the justification. Every dependency is an interface, so the storage can be swapped for a database and the fee can be swapped for a tiered policy without touching the service. The service holds no state of its own, so it can be tested with fakes in milliseconds.
Two things to avoid. Do not design more than the requirement asks for, because every speculative class is a liability you will have to defend. And do not go silent, because thinking out loud is what the interviewer is assessing. A short answer that names the trade-off you are making beats a long one that never admits a compromise.