Design thinking practice
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's messy code shows the same few problems again and again: classes that build their own helpers, a subclass for every mix, code that disagrees with its diagram. Each has a standard fix you can apply in minutes.
Smell 1: a class that creates its own dependencies
A smell is a sign in the code that a design problem may be hiding. It is not a bug: the program works, but it will be hard to change or test.
A class that calls new on its collaborators is welded to them. Below, a ShopLite Checkout that needs a database, a payment account and a mail server just to be tested.
class Checkout { private final MySqlStockDao stock = new MySqlStockDao("jdbc:mysql://localhost/shoplite"); private final CardNetworkClient gateway = new CardNetworkClient("live-key"); private final SmtpMailer mail = new SmtpMailer("smtp.shoplite.in"); // testing Checkout now needs a database, a payment account and a mail server}Example 1 · Checkout with three injected seams, tested with lambdas
import java.util.ArrayList;import java.util.List;
interface StockService { boolean reserve(String product, int qty);}
interface PaymentGateway { boolean charge(String orderId, double amount);}
interface NotificationService { void send(String to, String text);}
class Checkout { private final StockService stock; private final PaymentGateway gateway; private final NotificationService notifications;
Checkout(StockService stock, PaymentGateway gateway, NotificationService notifications) { this.stock = stock; this.gateway = gateway; this.notifications = notifications; }
String place(String orderId, String product, int qty, double amount, String contact) { if (!stock.reserve(product, qty)) return orderId + ": out of stock"; if (!gateway.charge(orderId, amount)) return orderId + ": payment declined"; notifications.send(contact, orderId + " confirmed"); return orderId + ": confirmed"; }}
public class CheckoutWiringDemo { public static void main(String[] args) { List<String> outbox = new ArrayList<>(); StockService stock = (product, qty) -> !product.equals("Smart watch"); // fake: watches sold out PaymentGateway gateway = (id, amount) -> amount <= 5000; // fake: declines above 5000 NotificationService notifications = (to, text) -> outbox.add(to + ": " + text);
Checkout checkout = new Checkout(stock, gateway, notifications); System.out.println(checkout.place("ORD-1", "Earbuds", 1, 1499, "asha@mail.com")); System.out.println(checkout.place("ORD-2", "Smart watch", 1, 2999, "ravi@mail.com")); System.out.println(checkout.place("ORD-3", "Laptop bag", 3, 7500, "meena@mail.com")); System.out.println("Messages sent: " + outbox); }}ORD-1: confirmed ORD-2: out of stock ORD-3: payment declined Messages sent: [asha@mail.com: ORD-1 confirmed]
What this code does
- Each fake is one lambda, because every seam is a one-method interface. All three paths (confirmed, out of stock, declined) run in milliseconds with no real systems.
- The outbox list proves that only the confirmed order sent a message, which is easy to check with a fake and hard to check with a real mail server.
The fix is always the same three steps: put an interface at each seam, take the interfaces in the constructor, and move the new calls to main (or let Spring do it). Tests then pass small fakes, often just lambdas.
Common mistake: adding the interface but leaving new inside the class. The class is still welded, so check that no concrete new remains.
Order of execution
Un-weld a class
Put the steps of the standard fix in order.
Smell 2: a subclass for every mix of features
Shipping add-ons show the same explosion as notifiers: ExpressGiftWrapShipping, GiftWrapInsuredShipping and so on. Below, the fix with one small class per add-on.
Example 2 · Shipping add-ons by composition
import java.util.List;import java.util.stream.Collectors;
interface ShippingAddOn { String name(); double charge(double orderTotal);}
class ExpressAddOn implements ShippingAddOn { public String name() { return "Express"; } public double charge(double orderTotal) { return 99; }}
class GiftWrapAddOn implements ShippingAddOn { public String name() { return "Gift wrap"; } public double charge(double orderTotal) { return 49; }}
class InsuranceAddOn implements ShippingAddOn { public String name() { return "Insurance"; } public double charge(double orderTotal) { return orderTotal * 0.01; }}
class Shipment { private static final double BASE = 40; private final List<ShippingAddOn> addOns;
Shipment(List<ShippingAddOn> addOns) { this.addOns = List.copyOf(addOns); }
double charge(double orderTotal) { double total = BASE; for (ShippingAddOn addOn : addOns) total += addOn.charge(orderTotal); return total; }
String describe() { if (addOns.isEmpty()) return "Standard"; return "Standard + " + addOns.stream().map(ShippingAddOn::name).collect(Collectors.joining(" + ")); }}
public class ShippingAddOnsDemo { public static void main(String[] args) { double orderTotal = 2000; List<List<ShippingAddOn>> choices = List.of( List.of(), List.of(new ExpressAddOn()), List.of(new ExpressAddOn(), new GiftWrapAddOn()), List.of(new GiftWrapAddOn(), new InsuranceAddOn())); for (List<ShippingAddOn> choice : choices) { Shipment shipment = new Shipment(choice); System.out.printf("%s: Rs %.2f%n", shipment.describe(), shipment.charge(orderTotal)); } }}Standard: Rs 40.00 Standard + Express: Rs 139.00 Standard + Express + Gift wrap: Rs 188.00 Standard + Gift wrap + Insurance: Rs 109.00
What this code does
- Three add-on classes and one
Shipmentcover every mix; with subclasses the same mixes would need seven shipping classes. - Insurance is 1% of the order total (Rs 20 on Rs 2000), so each add-on can use the order total in its own way.
The fix is composition: one small class per add-on behind a ShippingAddOn interface, and one Shipment that holds a list of them. Any mix is just a different list, built at run time from what the customer ticked.
With inheritance each new add-on doubles the number of classes; with composition it adds exactly one.
Smell 3: code that disagrees with its diagram
A diagram is a promise. Cart ◆── CartItem says the cart owns its items. Below, code that breaks that promise, then code that keeps it.
Example 3 · Code that keeps the composition promise
import java.util.ArrayList;import java.util.List;
record Product(String name, double price) {}
class CartItem { final Product product; int qty;
CartItem(Product product, int qty) { this.product = product; this.qty = qty; }
double amount() { return product.price() * qty; }}
// Disagrees with Cart ◆── CartItem: items come from outside, and the caller still holds themclass LeakyCart { private final List<CartItem> items = new ArrayList<>();
void add(CartItem item) { items.add(item); }
double total() { double sum = 0; for (CartItem item : items) sum += item.amount(); return sum; }}
// Matches Cart ◆── CartItem: the cart creates and owns its itemsclass Cart { private final List<CartItem> items = new ArrayList<>();
void add(Product product, int qty) { if (qty < 1 || qty > 5) throw new IllegalArgumentException("qty must be 1 to 5"); items.add(new CartItem(product, qty)); }
double total() { double sum = 0; for (CartItem item : items) sum += item.amount(); return sum; }}
public class DiagramMatchDemo { public static void main(String[] args) { Product hoodie = new Product("Hoodie", 899);
CartItem item = new CartItem(hoodie, 1); LeakyCart leaky = new LeakyCart(); leaky.add(item); item.qty = 50; // changed behind the cart's back System.out.printf("Leaky cart total: Rs %.2f%n", leaky.total());
Cart cart = new Cart(); cart.add(hoodie, 1); System.out.printf("Owned cart total: Rs %.2f%n", cart.total()); try { cart.add(hoodie, 50); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } }}Leaky cart total: Rs 44950.00 Owned cart total: Rs 899.00 Rejected: qty must be 1 to 5
What this code does
LeakyCartstored an item thatmainstill held, soitem.qty = 50silently changed the cart total to 50 × 899.Cart.add(product, qty)creates theCartItemitself, as the filled diamond promises, and can check the quantity before storing it.
In the first version add(CartItem item) accepts an item built outside, so the caller can still change it behind the cart's back.
When code and diagram disagree, decide which one states the real intent and fix the other. For ownership, the usual fix is to let the whole create its parts, so it can also check them.
Find the bug
Does the code keep the promise?
Click the line that breaks the diagram.
The diagram says Cart ◆── CartItem: the cart owns its items.
Round 1 of 2Interview drill: SOLID and patterns
A common question is "How do SOLID principles relate to design patterns?" Below, one checkout where each type carries a principle and a pattern.
Example 4 · Principles and patterns in one checkout
interface DiscountRule { // Strategy: serves OCP double apply(double amount);}
interface PaymentGateway { // seam: serves DIP boolean charge(String orderId, double amount);}
interface NotificationService { void send(String to, String text);}
class OldSmsApi { void sendText(String mobile, String body) { System.out.println("[SMS " + mobile + "] " + body); }}
class SmsAdapter implements NotificationService { // Adapter: serves DIP private final OldSmsApi api;
SmsAdapter(OldSmsApi api) { this.api = api; }
public void send(String to, String text) { api.sendText("+91" + to, text); }}
class Checkout { private final DiscountRule discount; private final PaymentGateway gateway; private final NotificationService notifications;
Checkout(DiscountRule discount, PaymentGateway gateway, NotificationService notifications) { this.discount = discount; this.gateway = gateway; this.notifications = notifications; }
void place(String orderId, double amount, String phone) { double toPay = discount.apply(amount); if (gateway.charge(orderId, toPay)) { notifications.send(phone, String.format("%s paid Rs %.2f", orderId, toPay)); } }}
public class PrinciplesToPatternsDemo { public static void main(String[] args) { PaymentGateway gateway = (id, amount) -> true; NotificationService sms = new SmsAdapter(new OldSmsApi());
new Checkout(amount -> amount, gateway, sms).place("ORD-41", 1200, "9876543210"); new Checkout(amount -> amount * 0.9, gateway, sms).place("ORD-42", 1200, "9876543210"); new Checkout(amount -> Math.max(0, amount - 150), gateway, sms).place("ORD-43", 1200, "9876543210"); }}[SMS +919876543210] ORD-41 paid Rs 1200.00 [SMS +919876543210] ORD-42 paid Rs 1080.00 [SMS +919876543210] ORD-43 paid Rs 1050.00
What this code does
- The comments name the principle each piece serves: Strategy for discounts (OCP), an Adapter for the old SMS API (DIP), small interfaces (ISP), one job for
Checkout(SRP). - Three discount rules ran through the same
Checkoutwith no edits to it. That sentence is the core of a good interview answer.
A strong answer has three parts: principles are goals, patterns are tested ways to reach them, and both rest on programming to interfaces and composition.
Give two concrete pairs: Strategy lets new rules arrive as new classes (Open/Closed), and Adapter plus constructor injection let checkout depend on its own interface instead of a vendor's class (Dependency Inversion). End with the cost: a pattern is worth it only when the change it prepares for is real.
Next step
Check your understanding
12 quick questions