SOLID in one page
medium 45 minFive principles for classes that can be changed without fear: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Watch lesson5:16
Alert service, complete
Read it, run it, change a line and run it again.
Loading editor…
All five letters in one program. The contract test near the end runs for each kind of sender.
The same in Java
import java.util.*;record Alert(String severity, String host, String message) {}record Receipt(boolean ok, String detail) {}interface Sender { String name(); /** The whole text, or Receipt(false, why). Never throws for a failed delivery. */ Receipt send(String to, String text);}interface History { void add(String entry);}class AlertFormatter { String format(Alert a) { return "[" + a.severity().toUpperCase(Locale.ROOT) + "] " + a.host() + ": " + a.message(); }}class AlertService { private final AlertFormatter formatter; private final List<Sender> senders; private final History history; AlertService(AlertFormatter formatter, List<Sender> senders, History history) { this.formatter = formatter; this.senders = List.copyOf(senders); this.history = history; } int notify(Alert alert, String to) { String text = formatter.format(alert); int delivered = 0; for (Sender s : senders) { Receipt r = s.send(to, text); history.add(s.name() + (r.ok() ? " ok" : " failed: " + r.detail())); if (r.ok()) delivered++; } if (delivered == 0) history.add("NOBODY WAS TOLD: " + text); return delivered; }}interface Smtp { void mail(String to, String text); }interface Gateway { boolean push(String number, String part); }class EmailSender implements Sender { private final Smtp smtp; EmailSender(Smtp smtp) { this.smtp = smtp; } public String name() { return "email"; } public Receipt send(String to, String text) { try { smtp.mail(to, text); } catch (IllegalStateException down) { return new Receipt(false, String.valueOf(down.getMessage())); } return new Receipt(true, ""); }}class SmsSender implements Sender { private static final int LIMIT = 160; private final Gateway gateway; private final Map<String, String> numbers; SmsSender(Gateway gateway, Map<String, String> numbers) { this.gateway = gateway; this.numbers = numbers; } public String name() { return "sms"; } public Receipt send(String to, String text) { String number = numbers.get(to); if (number == null) return new Receipt(false, "no number for " + to); int parts = 0; for (int i = 0; i < text.length(); i += LIMIT) { if (!gateway.push(number, text.substring(i, Math.min(text.length(), i + LIMIT)))) return new Receipt(false, "gateway refused"); parts++; } return new Receipt(true, parts + " parts"); }}class ChatSender implements Sender { public String name() { return "chat"; } public Receipt send(String to, String text) { return new Receipt(true, ""); }}public class Main { public static void main(String[] args) { List<String> out = new ArrayList<>(); List<Sender> senders = List.of( new EmailSender((to, text) -> { throw new IllegalStateException("smtp down"); }), new SmsSender((number, part) -> out.add(part), Map.of("ops", "+1")), new ChatSender()); AlertService service = new AlertService(new AlertFormatter(), senders, System.out::println); System.out.println(service.notify(new Alert("critical", "db1", "disk 95% full"), "ops")); }}The same in TypeScript
interface Alert { readonly severity: string; readonly host: string; readonly message: string;}interface Receipt { readonly ok: boolean; readonly detail: string;}interface Sender { readonly name: string; /** The whole text, or ok: false with a reason. Never throws for a failed delivery. */ send(to: string, text: string): Receipt;}interface History { add(entry: string): void;}class AlertFormatter { format(a: Alert): string { return "[" + a.severity.toUpperCase() + "] " + a.host + ": " + a.message; }}class AlertService { private readonly senders: readonly Sender[]; constructor( private readonly formatter: AlertFormatter, senders: readonly Sender[], private readonly history: History, ) { this.senders = [...senders]; } notify(alert: Alert, to: string): number { const text = this.formatter.format(alert); let delivered = 0; for (const s of this.senders) { const r = s.send(to, text); this.history.add(s.name + (r.ok ? " ok" : " failed: " + r.detail)); if (r.ok) delivered++; } if (delivered === 0) this.history.add("NOBODY WAS TOLD: " + text); return delivered; }}interface Smtp { mail(to: string, text: string): void }interface Gateway { push(number: string, part: string): boolean }class EmailSender implements Sender { readonly name = "email"; constructor(private readonly smtp: Smtp) {} send(to: string, text: string): Receipt { try { this.smtp.mail(to, text); } catch (e) { return { ok: false, detail: String(e) }; } return { ok: true, detail: "" }; }}class SmsSender implements Sender { readonly name = "sms"; constructor(private readonly gateway: Gateway, private readonly numbers: Record<string, string>) {} send(to: string, text: string): Receipt { const number = this.numbers[to]; if (number === undefined) return { ok: false, detail: "no number for " + to }; let parts = 0; for (let i = 0; i < text.length; i += 160) { if (!this.gateway.push(number, text.slice(i, i + 160))) return { ok: false, detail: "gateway refused" }; parts++; } return { ok: true, detail: parts + " parts" }; }}class ChatSender implements Sender { readonly name = "chat"; send(): Receipt { return { ok: true, detail: "" }; }}const out: string[] = [];const senders: Sender[] = [ new EmailSender({ mail: () => { throw new Error("smtp down"); } }), new SmsSender({ push: (_n, part) => out.push(part) > 0 }, { ops: "+1" }), new ChatSender(),];const service = new AlertService(new AlertFormatter(), senders, { add: (e) => console.log(e) });console.log(service.notify({ severity: "critical", host: "db1", message: "disk 95% full" }, "ops"));