Most SOLID explanations use shapes, animals or bank accounts. They make the principles sound obvious and leave you no better at applying them to the class in front of you. This post does the opposite: one real class from one of our services, refactored one principle at a time, with the test that kept each step safe.
The examples are Python 3.12, but nothing here depends on the language.
The starting point
NotificationService sent order updates to customers. Over two years it grew to about 300 lines. A
trimmed version:
class NotificationService:
def __init__(self):
self.smtp = smtplib.SMTP(os.environ["SMTP_HOST"])
self.db = psycopg.connect(os.environ["DATABASE_URL"])
def notify(self, order_id: int, event: str):
row = self.db.execute("SELECT email, phone, locale, prefs FROM customers c "
"JOIN orders o ON o.customer_id = c.id WHERE o.id = %s",
(order_id,)).fetchone()
email, phone, locale, prefs = row
if event == "shipped":
subject = "Your order is on the way" if locale == "en" else "Ihre Bestellung ist unterwegs"
body = f"Order {order_id} has shipped."
elif event == "delivered":
subject = "Delivered" if locale == "en" else "Zugestellt"
body = f"Order {order_id} was delivered."
else:
raise ValueError(event)
if prefs.get("email", True):
self.smtp.sendmail("orders@example.com", email, f"Subject: {subject}\n\n{body}")
if prefs.get("sms") and phone:
requests.post("https://sms.example.com/send", json={"to": phone, "text": body}, timeout=5)
self.db.execute("INSERT INTO notification_log (order_id, event) VALUES (%s, %s)",
(order_id, event))
Real problems we had with it: it could not be tested without a database and an SMTP server; adding push notifications meant editing the core method; and a translation fix required a deploy of the code that talks to the SMS provider.
Step 0: a characterisation test
Before changing structure, pin current behaviour. We wrote one test that runs the class against a test database and a local SMTP sink, and records what was sent:
def test_shipped_en_sends_email_and_sms(db, smtp_sink, sms_sink):
order = make_order(locale="en", prefs={"email": True, "sms": True})
NotificationService().notify(order.id, "shipped")
assert smtp_sink.subjects == ["Your order is on the way"]
assert sms_sink.texts == [f"Order {order.id} has shipped."]
Slow and ugly, but it lets every step below be checked against the original behaviour.
S: single responsibility
The usual phrasing, "a class should have one reason to change", is easier to apply if you ask who asks for changes. For this class there were four groups: product (message wording), the platform team (SMTP and SMS providers), data (how customers and preferences are stored), and compliance (the log).
We split along those lines:
class CustomerDirectory: # data team
def contact_for_order(self, order_id) -> Contact: ...
class MessageCatalog: # product
def render(self, event: str, locale: str, order_id: int) -> Message: ...
class EmailSender: # platform
def send(self, to: str, msg: Message) -> None: ...
class SmsSender: # platform
def send(self, to: str, msg: Message) -> None: ...
class NotificationLog: # compliance
def record(self, order_id: int, event: str) -> None: ...
NotificationService.notify now only coordinates. The characterisation test still passes. Nothing is
abstract yet; we just moved code.
O: open for extension, closed for modification
The next request was push notifications. In the old shape, that meant another if inside notify.
Open/closed asks for the opposite: add behaviour by adding code, not by editing working code.
We introduced a channel interface and let each channel decide whether it applies to a contact:
class Channel(Protocol):
def applies_to(self, contact: Contact) -> bool: ...
def send(self, contact: Contact, msg: Message) -> None: ...
class NotificationService:
def __init__(self, directory, catalog, channels: list[Channel], log):
...
def notify(self, order_id: int, event: str) -> None:
contact = self.directory.contact_for_order(order_id)
msg = self.catalog.render(event, contact.locale, order_id)
for channel in self.channels:
if channel.applies_to(contact):
channel.send(contact, msg)
self.log.record(order_id, event)
Push became a new PushChannel class and one line in the wiring. notify did not change.
One caution. Open/closed is a bet on where change will come from. We were confident new channels would
keep arriving. We were not confident about new event types, so we left MessageCatalog as a plain
dictionary of templates rather than building a plugin system for events nobody had asked for.
L: Liskov substitution
Every Channel must honour the same contract. The contract we wrote down in the docstring: send either
delivers or raises DeliveryError; it never swallows failures and never blocks longer than five seconds.
The first version of PushChannel broke this. When a device token was missing it returned quietly,
which meant the log said "notified" when nothing was sent. That is a Liskov violation: code written
against Channel could no longer trust what send returning meant.
We caught it with a contract test run against every channel:
@pytest.mark.parametrize("channel", all_channels_with_failing_transport())
def test_channel_raises_on_failed_delivery(channel, contact, message):
with pytest.raises(DeliveryError):
channel.send(contact, message)
The same test style works for any interface with more than one implementation. It turns "behaves like the base type" from a hope into a check.
I: interface segregation
The platform team wanted a retry worker that resends failed messages. Their first draft depended on the
whole NotificationService, which pulled in the customer directory and the catalog the worker never
used.
Interface segregation says clients should not depend on methods they do not use. The worker only needs
"send this already-rendered message on this channel", which Channel.send already is. So the worker
depends on Channel and nothing else. In Python we express these small interfaces as Protocols, so
there is no inheritance needed: any class with the right methods fits.
In practice this principle mostly shows up as "do not pass the big object when a small one will do".
D: dependency inversion
The original class created its own SMTP connection and database connection in __init__. That is why it
was untestable. Dependency inversion says high-level policy (when and what to notify) should depend on
abstractions, and the concrete details (SMTP, Postgres) should be plugged in from outside.
After the earlier steps this was nearly done already. The remaining piece was a composition root, one place that builds the real objects:
def build_notification_service(settings) -> NotificationService:
return NotificationService(
directory=PgCustomerDirectory(settings.database_url),
catalog=MessageCatalog.from_files(settings.templates_dir),
channels=[EmailChannel(SmtpTransport(settings.smtp_host)),
SmsChannel(SmsHttpClient(settings.sms_url)),
PushChannel(PushClient(settings.push_key))],
log=PgNotificationLog(settings.database_url),
)
Unit tests now build the service with in-memory fakes and run in milliseconds:
def test_sms_only_when_opted_in():
sms = FakeChannel(applies=lambda c: c.prefs.sms)
svc = NotificationService(FakeDirectory(prefs={"sms": False}), catalog, [sms], FakeLog())
svc.notify(1, "shipped")
assert sms.sent == []
We kept the slow characterisation test as an integration test, so the real wiring is still exercised.
Where SOLID was overkill
Applying every principle everywhere is its own design smell. Things we chose not to do:
- No interface for
MessageCatalog. It has one implementation and no plans for another. AProtocolwith one implementer is indirection without benefit. - No separate class per event type. Two events, both one-line templates. A class hierarchy for them would be bigger than the code it replaced.
- No dependency injection framework. One composition function of twenty lines is easier to read and debug than a container configured by decorators.
- Not splitting
EmailChannelinto "formatter" and "transport" interfaces. We did split them as classes, because the transport is reused, but we did not invent abstractions for the formatter.
A useful rule: introduce an abstraction when you have a second implementation, a test that needs a fake, or a concrete, scheduled change. Not before.
Results
| Measure | Before | After |
|---|---|---|
| Unit test time for notification logic | 14 s (needed DB + SMTP) | 0.3 s |
| Files touched to add push channel | 1 core file, 60-line diff | 1 new file + 1 wiring line |
| Lines in the coordinating class | ~300 | 35 |
| Total lines including new classes | ~300 | ~380 |
The total line count went up. That is normal. The goal was not less code; it was code where each change lands in one predictable place and can be tested on its own.
Summary
- Run SOLID one principle at a time on real code, with a characterisation test before you start.
- Single responsibility is easiest to apply by asking who requests changes.
- Open/closed is a bet on where change will come from; make it only where you have evidence.
- Write contract tests for every interface with more than one implementation.
- Stop when an abstraction would have one implementation and no test that needs it.
References: typing.Protocol, pytest parametrize.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.