Final challenge: which principle?
After this: Read five small programs and name the principle each one breaks.
You have met all five rules. Each one has a sign you can spot in code, and a usual fix:
| Rule | The sign | The usual fix |
|---|---|---|
| S, single responsibility | one class changes for several kinds of request | one class per job |
| O, open/closed | an if with one branch per kind, edited for every new kind | one class per kind, behind an interface |
| L, Liskov substitution | a child that changes or refuses what its parent promises | make them siblings under a smaller interface |
| I, interface segregation | a class that fills methods with errors because an interface demands them | split the interface into small ones |
| D, dependency inversion | a class that creates its own file, database or sender | depend on an interface, and hand the object in |
L and I can look alike, because in both a class refuses a method. Ask where the refused method comes from. If it comes from a parent class whose own version works, and the child changes it, that is L. If it comes from an interface that asks a class for something it could never do, that is I.
This challenge shows five small programs, each with its output. Each one runs, and each one breaks one of the five rules. Name the rule. The feedback on every answer says why, and what the fix would be. Every program is shown in Python and in Java, and the answers are the same in both. Each step is scored on its own, and hints work as they do in the lessons.
The pricing team, the designer and the email team each send this class a change request in the same week. Which principle does it break?
class Invoice: def __init__(self, items): self.items = items self.outbox = []
def total(self): return sum(self.items)
def text(self): return f"Invoice: {self.total()} rupees"
def email(self, to): self.outbox.append(to + ": " + self.text()) return "sent to " + to
bill = Invoice([300, 450])print(bill.text())print(bill.email("asha@example.com"))Invoice: 750 rupees sent to asha@example.com
import java.util.ArrayList;import java.util.List;
class Invoice { private List<Integer> items; private List<String> outbox = new ArrayList<>();
Invoice(List<Integer> items) { this.items = items; }
int total() { int sum = 0; for (int i : items) { sum += i; } return sum; }
String text() { return "Invoice: " + total() + " rupees"; }
String email(String to) { outbox.add(to + ": " + text()); return "sent to " + to; }}
public class Main { public static void main(String[] args) { Invoice bill = new Invoice(List.of(300, 450)); System.out.println(bill.text()); System.out.println(bill.email("asha@example.com")); }}Invoice: 750 rupees sent to asha@example.com
The shop wants same-day shipping at 150 rupees per kg, and next year a fourth kind. Which principle does this code break?
def shipping_cost(kind, kg): if kind == "standard": return 40 * kg elif kind == "express": return 90 * kg else: raise ValueError("unknown shipping: " + kind)
print(shipping_cost("standard", 2))print(shipping_cost("express", 2))80 180
public class Main { static int shippingCost(String kind, int kg) { if (kind.equals("standard")) { return 40 * kg; } else if (kind.equals("express")) { return 90 * kg; } else { throw new IllegalArgumentException("unknown shipping: " + kind); } }
public static void main(String[] args) { System.out.println(shippingCost("standard", 2)); System.out.println(shippingCost("express", 2)); }}80 180
The rent function was written for accounts, and works for every Account with enough money. Which principle does FixedDeposit break?
class Account: def __init__(self, balance): self.balance = balance
def withdraw(self, amount): if amount > self.balance: raise ValueError("not enough money") self.balance -= amount
class FixedDeposit(Account): def withdraw(self, amount): raise ValueError("locked until the end of the term")
def pay_rent(account): account.withdraw(300) return account.balance
print(pay_rent(Account(1000)))try: print(pay_rent(FixedDeposit(1000)))except ValueError as e: print("error:", e)700 error: locked until the end of the term
class Account { protected int balance;
Account(int balance) { this.balance = balance; }
void withdraw(int amount) { if (amount > balance) { throw new IllegalArgumentException("not enough money"); } balance -= amount; }}
class FixedDeposit extends Account { FixedDeposit(int balance) { super(balance); }
void withdraw(int amount) { throw new IllegalArgumentException("locked until the end of the term"); }}
public class Main { static int payRent(Account account) { account.withdraw(300); return account.balance; }
public static void main(String[] args) { System.out.println(payRent(new Account(1000))); try { System.out.println(payRent(new FixedDeposit(1000))); } catch (IllegalArgumentException e) { System.out.println("error: " + e.getMessage()); } }}700 error: locked until the end of the term
A smart-home app has one interface for every device. Which principle does it break?
from abc import ABC, abstractmethod
class SmartDevice(ABC): @abstractmethod def turn_on(self): pass
@abstractmethod def set_temperature(self, degrees): pass
@abstractmethod def play_music(self, song): pass
class Lamp(SmartDevice): def turn_on(self): return "lamp on"
def set_temperature(self, degrees): raise NotImplementedError("a lamp has no temperature")
def play_music(self, song): raise NotImplementedError("a lamp cannot play music")
lamp = Lamp()print(lamp.turn_on())try: lamp.play_music("raga")except NotImplementedError as e: print("error:", e)lamp on error: a lamp cannot play music
interface SmartDevice { String turnOn(); void setTemperature(int degrees); void playMusic(String song);}
class Lamp implements SmartDevice { public String turnOn() { return "lamp on"; }
public void setTemperature(int degrees) { throw new UnsupportedOperationException("a lamp has no temperature"); }
public void playMusic(String song) { throw new UnsupportedOperationException("a lamp cannot play music"); }}
public class Main { public static void main(String[] args) { Lamp lamp = new Lamp(); System.out.println(lamp.turnOn()); try { lamp.playMusic("raga"); } catch (UnsupportedOperationException e) { System.out.println("error: " + e.getMessage()); } }}lamp on error: a lamp cannot play music
The team wants to send some alerts by SMS, and to test Alerts without sending any email. Which principle does this code break?
class EmailSender: def __init__(self): self.sent = []
def send(self, text): self.sent.append(text) return "email: " + text
class Alerts: def __init__(self): self.sender = EmailSender()
def warn(self, text): return self.sender.send("warning, " + text)
alerts = Alerts()print(alerts.warn("disk almost full"))email: warning, disk almost full
import java.util.ArrayList;import java.util.List;
class EmailSender { private List<String> sent = new ArrayList<>();
String send(String text) { sent.add(text); return "email: " + text; }}
class Alerts { private EmailSender sender;
Alerts() { this.sender = new EmailSender(); }
String warn(String text) { return sender.send("warning, " + text); }}
public class Main { public static void main(String[] args) { Alerts alerts = new Alerts(); System.out.println(alerts.warn("disk almost full")); }}email: warning, disk almost full
- Name the principle each of five small programs breaks: one class with three jobs, an if per kind, a child that refuses its parent's method, an interface too big for a lamp, and a sender created inside.
- Say the fix for each, in a sentence.
- Tell the Liskov rule from interface segregation: a child breaking a parent's promise, against an interface asking for more than a class can do.