SOLID as design decisions, not definitions
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's first OrderService prices the cart, charges the card and sends the email in one method, so every change request lands in it. Each SOLID principle answers one practical question about such a change.
SOLID in one line each
SOLID is five rules of thumb for deciding where code should live and what it should depend on: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion.
The OOP section taught each principle. Here is the one-line version to keep in your head:
- S, Single Responsibility: a class has one reason to change.
- O, Open/Closed: add new behaviour by adding code, not by editing working code.
- L, Liskov Substitution: a subtype must keep every promise of its parent type.
- I, Interface Segregation: many small interfaces beat one fat one.
- D, Dependency Inversion: high-level code depends on abstractions, not on concrete classes.
The rest of this lesson follows ShopLite's order flow, the app that Stage 5 refactors: an Order is priced, paid with a PaymentMethod and confirmed by a NotificationService. Each section shows a before and after, plus the question that drove the change.
double for rupees to keep the code short. Real payment code uses BigDecimal or whole paise in a long.SRP decision: split the god OrderService
A god class is a class that does many unrelated jobs, so almost every change request lands in it.
A first OrderService often prices the cart, charges the card and sends the email in one method. Below, that class, then the same work split into three.
Example 1 · SRP: one god class split into three
import java.util.List;
record Item(String name, double price, int qty) {}
// Before: one class prices, charges and sends messagesclass GodOrderService { void placeOrder(String customer, List<Item> items) { double total = 0; for (Item i : items) total += i.price() * i.qty(); if (total >= 1000) total = total * 0.9; // 10% off on Rs 1000 or more System.out.printf("Charging Rs %.2f to %s's card%n", total, customer); System.out.println("Email to " + customer + ": order placed"); }}
// After: one reason to change per classclass PriceCalculator { double total(List<Item> items) { double total = 0; for (Item i : items) total += i.price() * i.qty(); return total >= 1000 ? total * 0.9 : total; }}
class PaymentService { void charge(String customer, double amount) { System.out.printf("Charging Rs %.2f to %s's card%n", amount, customer); }}
class OrderNotifier { void orderPlaced(String customer) { System.out.println("Email to " + customer + ": order placed"); }}
class OrderService { private final PriceCalculator prices = new PriceCalculator(); private final PaymentService payments = new PaymentService(); private final OrderNotifier notifier = new OrderNotifier();
void placeOrder(String customer, List<Item> items) { double total = prices.total(items); payments.charge(customer, total); notifier.orderPlaced(customer); }}
public class SrpSplitDemo { public static void main(String[] args) { List<Item> cart = List.of(new Item("Hoodie", 899, 1), new Item("Earbuds", 1499, 1));
System.out.println("Before:"); new GodOrderService().placeOrder("Asha", cart);
System.out.println("After:"); new OrderService().placeOrder("Asha", cart);
double pens = new PriceCalculator().total(List.of(new Item("Pen set", 150, 2))); System.out.printf("Price check alone: Rs %.2f%n", pens); }}Before: Charging Rs 2158.20 to Asha's card Email to Asha: order placed After: Charging Rs 2158.20 to Asha's card Email to Asha: order placed Price check alone: Rs 300.00
What this code does
- Both versions print the same thing, so the split changed the design, not the behaviour. Question asked: who requests changes to pricing, payment and messages? Three different teams.
- The last line uses
PriceCalculatoron its own. Pricing can now be checked without charging a card or sending an email. OrderServicestill callsnewfor its three helpers. That is a DIP problem, fixed in Example 5.
The question that drives the split: who asks for each change? The marketing team changes discounts, the payments team changes the card provider, the support team changes the email text. Three groups of people mean three reasons to change, so three classes.
Find the bug
Find the extra reason to change
Click the line that does not belong in OrderService.
Marketing changes discounts often. Which line drags them into OrderService?
Round 1 of 2OCP and LSP decision: new payment types and broken contracts
A contract is the set of promises a type makes: what inputs it accepts, what it returns and what it never does. A subtype must keep every promise of its parent type.
Two questions drive these principles. When a new case arrives, do you add a class or edit a tested one? Below is the if chain that forces an edit every time.
void complete(String orderId, double amount, String type) { if (type.equals("CARD")) { /* charge card */ } else if (type.equals("UPI")) { /* send UPI request */ } // adding "WALLET" means editing this tested method again}Example 2 · OCP: a new payment type without editing Checkout
interface PaymentMethod { String name(); String pay(double amount);}
class CardPayment implements PaymentMethod { public String name() { return "Card"; }
public String pay(double amount) { return String.format("card charged Rs %.2f", amount); }}
class UpiPayment implements PaymentMethod { private final String upiId;
UpiPayment(String upiId) { this.upiId = upiId; }
public String name() { return "UPI"; }
public String pay(double amount) { return String.format("collect request of Rs %.2f sent to %s", amount, upiId); }}
// Added months later: a new class, and not one line of Checkout changedclass WalletPayment implements PaymentMethod { private double balance;
WalletPayment(double balance) { this.balance = balance; }
public String name() { return "Wallet"; }
public String pay(double amount) { balance -= amount; return String.format("wallet paid Rs %.2f, Rs %.2f left", amount, balance); }}
class Checkout { void complete(String orderId, double amount, PaymentMethod method) { System.out.println(orderId + " [" + method.name() + "] " + method.pay(amount)); }}
public class OcpPaymentDemo { public static void main(String[] args) { Checkout checkout = new Checkout(); checkout.complete("ORD-101", 499, new CardPayment()); checkout.complete("ORD-102", 1250, new UpiPayment("asha@okaxis")); checkout.complete("ORD-103", 300, new WalletPayment(1000)); }}ORD-101 [Card] card charged Rs 499.00 ORD-102 [UPI] collect request of Rs 1250.00 sent to asha@okaxis ORD-103 [Wallet] wallet paid Rs 300.00, Rs 700.00 left
What this code does
Checkout.completeonly knows thePaymentMethodinterface. Question asked: will the next payment type be a new class or an edit? Here it is a new class.WalletPaymentwas added without touchingCheckout, so the tested checkout code cannot break because of it.
Example 3 · LSP: a gift card that breaks the contract, and the fix
interface PaymentMethod { String pay(double amount);
// Contract: pay() must succeed whenever canPay() says true default boolean canPay(double amount) { return amount > 0; }}
class WalletPayment implements PaymentMethod { public String pay(double amount) { return String.format("wallet paid Rs %.2f", amount); }}
// Breaks the contract: canPay() says yes, then pay() throwsclass BrokenGiftCard extends WalletPayment { @Override public String pay(double amount) { if (amount > 2000) throw new IllegalStateException("gift card limit is Rs 2000"); return String.format("gift card paid Rs %.2f", amount); }}
// Keeps the contract: the limit is visible through canPay()class GiftCardPayment extends WalletPayment { @Override public boolean canPay(double amount) { return amount > 0 && amount <= 2000; }
@Override public String pay(double amount) { return String.format("gift card paid Rs %.2f", amount); }}
public class LspContractDemo { static void checkout(String orderId, PaymentMethod method, double amount) { if (!method.canPay(amount)) { System.out.printf("%s: cannot pay Rs %.2f this way, choose another method%n", orderId, amount); return; } System.out.println(orderId + ": " + method.pay(amount)); }
public static void main(String[] args) { checkout("ORD-201", new WalletPayment(), 2500); checkout("ORD-202", new GiftCardPayment(), 1500); checkout("ORD-203", new GiftCardPayment(), 2500); try { checkout("ORD-204", new BrokenGiftCard(), 2500); } catch (IllegalStateException e) { System.out.println("ORD-204: checkout crashed, " + e.getMessage()); } }}ORD-201: wallet paid Rs 2500.00 ORD-202: gift card paid Rs 1500.00 ORD-203: cannot pay Rs 2500.00 this way, choose another method ORD-204: checkout crashed, gift card limit is Rs 2000
What this code does
BrokenGiftCardinheritscanPay(which says yes for 2500) but then throws inpay. Checkout did everything right and still crashed: that is an LSP violation.GiftCardPaymentputs its limit intocanPay, which is part of the contract. Checkout asks first and shows a friendly message for ORD-203.- Question asked: can checkout use every subtype without knowing which one it got? Only the fixed version says yes.
OCP: checkout with an if (type.equals("CARD")) chain must be edited, retested and redeployed for every new payment type. Checkout that talks only to a PaymentMethod interface accepts a new WalletPayment with zero edits.
LSP: can checkout use every subtype without knowing which one it got? A subclass that refuses inputs the parent accepts, or throws where the parent never threw, breaks the contract, and checkout crashes on a case it was told could not happen.
ISP and DIP decision: small interfaces, injected dependencies
A fat interface has so many methods that its implementers must support things they do not do, and end up throwing or doing nothing for the extra methods.
A fat Notifier with sendEmail, sendSms and sendPush forces an SMS-only class to throw for the other two. Below, the split, then checkout receiving its notifier.
Example 4 · ISP: splitting a fat Notifier
// Before: one fat interfaceinterface Notifier { void sendEmail(String to, String text); void sendSms(String phone, String text); void sendPush(String deviceId, String text);}
class SmsOnlyNotifier implements Notifier { public void sendEmail(String to, String text) { throw new UnsupportedOperationException("this notifier has no email"); }
public void sendSms(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }
public void sendPush(String deviceId, String text) { throw new UnsupportedOperationException("this notifier has no push"); }}
// After: small interfaces, each class implements only what it can dointerface EmailSender { void sendEmail(String to, String text);}
interface SmsSender { void sendSms(String phone, String text);}
class SmsGateway implements SmsSender { public void sendSms(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }}
class DeliveryAlerts { private final SmsSender sms; // needs SMS only, so asks for SMS only
DeliveryAlerts(SmsSender sms) { this.sms = sms; }
void outForDelivery(String phone, String orderId) { sms.sendSms(phone, orderId + " is out for delivery"); }}
public class IspNotifierDemo { public static void main(String[] args) { Notifier fat = new SmsOnlyNotifier(); fat.sendSms("9876543210", "ORD-301 shipped"); try { fat.sendEmail("asha@mail.com", "ORD-301 shipped"); } catch (UnsupportedOperationException e) { System.out.println("Fat interface: " + e.getMessage()); }
new DeliveryAlerts(new SmsGateway()).outForDelivery("9876543210", "ORD-301");
EmailSender mailer = (to, text) -> System.out.println("Email to " + to + ": " + text); mailer.sendEmail("asha@mail.com", "Invoice for ORD-301"); }}SMS to 9876543210: ORD-301 shipped Fat interface: this notifier has no email SMS to 9876543210: ORD-301 is out for delivery Email to asha@mail.com: Invoice for ORD-301
What this code does
SmsOnlyNotifiermust havesendEmailandsendPushbecause the fat interface demands them, so it throws. A caller holding aNotifiercannot tell which methods are real.DeliveryAlertsasks for anSmsSenderonly. A one-method interface is also easy to supply as a lambda, as themailerline shows.
Example 5 · DIP: checkout receives its NotificationService
// Before: checkout creates its own concrete email classclass EmailSender { void send(String to, String text) { System.out.println("Email to " + to + ": " + text); }}
class TightCheckout { private final EmailSender email = new EmailSender(); // fixed forever
void place(String orderId, String customer) { System.out.println("Placed " + orderId); email.send(customer, orderId + " confirmed"); }}
// After: checkout depends on an abstraction that it receivesinterface NotificationService { void send(String to, String text);}
class EmailNotification implements NotificationService { public void send(String to, String text) { System.out.println("Email to " + to + ": " + text); }}
class SmsNotification implements NotificationService { public void send(String to, String text) { System.out.println("SMS to " + to + ": " + text); }}
class Checkout { private final NotificationService notifications;
Checkout(NotificationService notifications) { this.notifications = notifications; }
void place(String orderId, String customer) { System.out.println("Placed " + orderId); notifications.send(customer, orderId + " confirmed"); }}
public class DipCheckoutDemo { public static void main(String[] args) { System.out.println("Before:"); new TightCheckout().place("ORD-401", "asha@mail.com");
System.out.println("After:"); new Checkout(new EmailNotification()).place("ORD-402", "asha@mail.com"); new Checkout(new SmsNotification()).place("ORD-403", "9876543210"); }}Before: Placed ORD-401 Email to asha@mail.com: ORD-401 confirmed After: Placed ORD-402 Email to asha@mail.com: ORD-402 confirmed Placed ORD-403 SMS to 9876543210: ORD-403 confirmed
What this code does
TightCheckoutwritesnew EmailSender()itself, so switching to SMS means editing checkout.Checkoutdepends on theNotificationServiceabstraction and gets the real object through its constructor. Question asked: can I swap this without editing checkout? Now yes, as ORD-403 shows.
ISP asks: does every class that implements this interface really do every method? Split it so each class, and each caller, sees only what it uses.
DIP asks: can I swap this dependency without editing the class that uses it? With new EmailSender() inside, Checkout is welded to email. With a NotificationService from the constructor, the caller picks email, SMS or a fake. The next lesson works through that idea.
Predict the output
Which payments can refund?
Only some payments can refund. What does each snippet print?
Round 1 of 2
The question behind each change
A reason to change is a person or group who may ask for a change to a class, such as marketing asking for new discounts. A class with one reason to change has one responsibility.
SOLID is easier to apply as questions than as definitions. Before you change a design, ask the one that fits:
- SRP: who asks for changes to this class, and is it more than one group?
- OCP: will the next new case be a new class, or an edit to a tested one?
- LSP: can every subtype stand in for its parent without surprises?
- ISP: does any implementer throw or do nothing for a method it was forced to have?
- DIP: does this class call
newon something it might need to swap?
If the honest answer is "no change is coming here", leave the code simple. Principles serve change; they are not a score to maximise.
Next step
Check your understanding
11 quick questions