AlgoViz

SOLID in one page

medium 45 min

Five principles for classes that can be changed without fear: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.

Watch lesson5:16

Implementation

The complete program, with the letter that each line pays for.

The point: contracts first, then the service, then the details, and the wiring last. If the service can be written before any detail exists, D is done.

Line by line

Alert service

Alert service

What travels, and what the service needs from outside.

from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Protocol@dataclass(frozen=True)class Alert:    severity: str    host: str    message: str@dataclass(frozen=True)class Receipt:    ok: bool    detail: str = ""class Sender(Protocol):    name: str    def send(self, to: str, text: str) -> Receipt:        """The whole text, or Receipt(False, why). Never raises for a failed delivery."""class History(Protocol):    def add(self, entry: str) -> None: ...

Lines 6 to 16

Frozen, because several senders see the same alert. A sender that shortened the message in place would shorten it for the next one.

1 of 3

Why it is built this way

  • Failure is in the return type. With exceptions, each library would bring its own, and the service would have to know them.