In the previous lesson we learned to measure a design with two general ideas: high cohesion and low coupling. But when Íker opens the orders file and wonders where to cut, he needs something more concrete. The SOLID principles are five practical rules for designing classes and functions that can be changed without fear. In this lesson we will look at each one with the same outline: what it says, what it means in plain language, a fragment of Verdalia's code that violates it, what it looks like once corrected, and in which cases it is not worth applying.

What SOLID Is and What It Is For

SOLID is an acronym formed by the initials of five object-oriented design principles. The engineer Robert C. Martin gathered and popularized them in the early 2000s, although some are older.

The five principles are: single responsibility (SRP), open-closed (OCP), Liskov substitution (LSP), interface segregation (ISP), and dependency inversion (DIP). Their initials form the word SOLID.

All five pursue the same thing: that a change in requirements translates into a small, localized change in the code. They are, therefore, tools in the service of maintainability, the attribute of scenario QS-5.

Two warnings before we start:

  • They are principles, not laws. They guide a decision, but applying them has a cost: more classes, more files, and more indirection. That is why each section ends by pointing out when it is not worth it.
  • They need one Python tool: abstract classes. An abstract class defines which methods a type of object must have, without saying how they are implemented. You create one by inheriting from ABC and marking the methods with @abstractmethod. Python prevents you from creating objects of a class that has not implemented all the marked methods. In this lesson we will use them as interfaces, that is, as contracts.

S: Single Responsibility Principle

Statement. A class should have only one reason to change.

In plain language. Each class should answer to a single kind of change request. A practical way to check this is to ask who can request that the class change. If the answer includes several unrelated people or motives, the class has several responsibilities.

The Code That Violates It

OrderManager is the most feared class in the store: 1,400 lines and 38 methods. This is its main method, simplified:

# orders.py (simplified excerpt)
class OrderManager:
    def confirm_order(self, order_id):
        # Data access
        cursor = connection.cursor()
        cursor.execute(
            "SELECT amount, shipping_method, customer_email FROM orders WHERE id = %s",
            (order_id,),
        )
        amount, shipping_method, customer_email = cursor.fetchone()

        # Business rule: second copy of the shipping cost calculation
        if shipping_method == "express":
            cost = 8.90
        elif amount > 60:
            cost = 0.0
        else:
            cost = 4.95
        total = round(float(amount) + cost, 2)

        # Payment: direct call to PagoRaiz
        response = requests.post(
            "https://api.pagoraiz.example/v1/charges",
            json={"amount_cents": round(total * 100), "reference": f"ORD-{order_id}"},
            headers={"Authorization": config.PAGORAIZ_KEY},
        )
        if response.json()["status"] != "AUTHORIZED":
            return False

        # Data access again, and email notification
        cursor.execute("UPDATE orders SET status = 'confirmed' WHERE id = %s", (order_id,))
        connection.commit()
        server = smtplib.SMTP("smtp.mail.example", 587)
        server.sendmail("[email protected]", customer_email,
                        f"Order confirmed. Total: €{total}")
        return True

    # ... and 37 more methods: PDF invoices, exports, statistics

Who can request that this method change? Andrés, if the shipping cost rules change; PagoRaíz, if it changes how it receives charges; Lucía, if the database or the email server changes; and customer support, if the text of the email changes.

Four reasons to change in a single method. And every change forces you to recheck everything else, by hand, because there are no automated tests.

The Refactoring

Refactoring is improving the internal structure of the code without changing what it does. Íker splits the responsibilities into small classes:

@dataclass
class Order:
    id: int
    customer_email: str
    amount: float
    shipping_method: str = "standard"
    shipping_cost: float = 0.0
    status: str = "pending"

    @property
    def total(self):
        return round(self.amount + self.shipping_cost, 2)


class PostgresOrderRepository:
    """Single responsibility: store and retrieve orders."""
    def find(self, order_id): ...
    def save(self, order): ...


class PagoRaizGateway:
    """Single responsibility: talk to PagoRaiz."""
    def charge(self, reference, amount): ...


class SmtpNotifier:
    """Single responsibility: write and send emails."""
    def send_confirmation(self, order): ...


class OrderService:
    """Single responsibility: coordinate the steps of the confirmation."""

    def __init__(self):
        self._repository = PostgresOrderRepository()
        self._gateway = PagoRaizGateway()
        self._notifier = SmtpNotifier()

    def confirm(self, order_id):
        order = self._repository.find(order_id)
        order.shipping_cost = calculate_shipping_cost(order.amount, order.shipping_method)
        result = self._gateway.charge(f"ORD-{order.id}", order.total)
        if not result.accepted:
            return False
        order.status = "confirmed"
        self._repository.save(order)
        self._notifier.send_confirmation(order)
        return True

Explanation:

  • Order is a data class. The @dataclass decorator automatically generates the constructor from the list of fields. The total property is computed from the amount and the shipping cost.
  • Each class has one responsibility, described in its first line. The bodies marked with ... contain the same blocks as before, moved without changes.
  • The shipping cost rule is no longer copied: calculate_shipping_cost, from the shipping module created in the previous lesson, is called instead.
  • OrderService.confirm now reads like a list of steps. It knows nothing about SQL, HTTP, or email.
  • One defect remains: the constructor creates its three collaborators itself. We will fix that when we get to the letter D.

When It Is Not Worth It

  • In a thirty-line program used by a single person, splitting into four classes only adds noise.
  • When you split so much that each class has a single three-line method, following the flow means opening ten files. A responsibility is not “doing one thing,” but “changing for one reason.”

O: Open-Closed Principle

Statement. Code should be open for extension and closed for modification.

In plain language. Adding a new variant should consist of writing new code, not modifying code that already works. Every time tested code is touched, there is a risk of breaking it.

The Code That Violates It

Andrés has already warned that in November he will want to offer economy shipping. With the function from the previous lesson, the change would be this:

def calculate_shipping_cost(amount, method="standard"):
    if method == "standard":
        if amount > _FREE_SHIPPING_THRESHOLD:
            return 0.0
        return 4.95
    if method == "express":
        return 8.90
    if method == "economy":          # new branch inside existing code
        ...
    raise ValueError(f"Unknown shipping method: {method}")

Each new method adds a branch to the same function. Besides, the name shown to the customer and the delivery time of each method live in other functions, with if chains of their own. Adding a method means finding and modifying all of them.

The Refactoring

# verdalia/shipping/methods.py
from abc import ABC, abstractmethod

FREE_SHIPPING_THRESHOLD = 60.0


class ShippingMethod(ABC):
    """Contract that any shipping method fulfills."""

    code = ""
    name = ""

    @abstractmethod
    def calculate_cost(self, amount):
        """Returns the cost in euros: always a number greater than or equal to 0."""


class StandardShipping(ShippingMethod):
    code = "standard"
    name = "Standard shipping (48-72 hours)"

    def calculate_cost(self, amount):
        return 0.0 if amount > FREE_SHIPPING_THRESHOLD else 4.95


class ExpressShipping(ShippingMethod):
    code = "express"
    name = "Express shipping (24 hours)"

    def calculate_cost(self, amount):
        return 8.90


METHODS = [StandardShipping(), ExpressShipping()]


def calculate_shipping_cost(amount, method="standard"):
    for candidate in METHODS:
        if candidate.code == method:
            return candidate.calculate_cost(amount)
    raise ValueError(f"Unknown shipping method: {method}")

With this design, Íker checks how economy shipping would be added:

class EconomyShipping(ShippingMethod):
    code = "economy"
    name = "Economy shipping (5-7 days)"

    def calculate_cost(self, amount):
        return 0.0 if amount > FREE_SHIPPING_THRESHOLD else 2.95


METHODS.append(EconomyShipping())

for method in METHODS:
    print(f"{method.name}: €{method.calculate_cost(45.0):.2f}")

Output:

Standard shipping (48-72 hours): €4.95
Express shipping (24 hours): €8.90
Economy shipping (5-7 days): €2.95

Explanation:

  • ShippingMethod is the interface: every shipping method has a code, a name, and knows how to calculate its cost.
  • Each concrete method is a small class that gathers everything of its own: code, name, and rate. There are no more if chains scattered around.
  • METHODS is the list of available methods, and calculate_shipping_cost searches it. The module's public interface has not changed: the cart keeps calling the same function.
  • To add economy shipping, you write a new class and register it in the list. StandardShipping and ExpressShipping are not touched.

An honest nuance: there is always some point that has to be modified, in this case the METHODS list. The principle does not ask for that point to disappear, but for it to be unique and trivial.

When It Is Not Worth It

  • When you do not know along which axis the code will vary. Preparing extension points for imaginary changes complicates the design with no benefit.
  • When there are two cases that change once every few years. An if with two branches is perfectly readable. The moment to apply the principle is usually the arrival of the third variant.

L: Liskov Substitution Principle

Statement. Objects of a subclass must be usable in place of objects of their base class without the program ceasing to work correctly. The computer scientist Barbara Liskov formulated it in 1987.

In plain language. Whoever inherits from a class signs its contract. If the code expects a ShippingMethod, any shipping method must work for it, without surprises and without having to ask which concrete type it is.

The Code That Violates It

Encouraged by the result, Íker tries to incorporate the special transport for large trees, which today is quoted by phone:

class BulkyShipping(ShippingMethod):
    code = "bulky"
    name = "Special transport for large trees"

    def calculate_cost(self, amount):
        raise NotImplementedError("Cost is quoted by phone")


def shipping_options(amount, methods):
    """Prepares the list of options shown in the cart."""
    return [(method.name, method.calculate_cost(amount)) for method in methods]


shipping_options(45.0, METHODS + [BulkyShipping()])

Output:

NotImplementedError: Cost is quoted by phone

BulkyShipping inherits from ShippingMethod, but it does not fulfill its contract, which promises to always return a number. The result is that the cart page fails for every customer. The usual temptation is to patch the caller with a check of the concrete type using isinstance. That patch spreads to every place where shipping methods are used and undoes what the previous principle achieved.

The Refactoring

The right question is whether the special transport is really a shipping method, in the sense the code gives that term. There are two valid ways out:

  • Fulfill the contract, giving it a computable rate, if the business can set an automatic price.
  • Take it out of the hierarchy and model it as something else, for example a quote request, if the price depends on a manual assessment.

At Verdalia the price depends on each tree, so the special transport stays out of the hierarchy and continues to be handled by phone.

For a subclass to be substitutable, it must meet three conditions:

  • Not demand more than the base class: it must accept the same input data.
  • Not promise less: it must return the same type of result, with the same guarantees.
  • Not raise errors that the base class does not contemplate.

When It Is Not Worth It

This principle is not optional: if you use inheritance, you have to comply with it. What is optional is inheritance. When the “is a kind of” relationship feels forced, it is better not to inherit. We will see the alternative, composition, in the next lesson.

I: Interface Segregation Principle

Statement. No client should be forced to depend on methods it does not use.

In plain language. It is better to have several small interfaces, each designed for whoever uses it, than one large interface that serves everything.

The Code That Violates It

class NotificationCenter(ABC):
    @abstractmethod
    def send_confirmation(self, order): ...

    @abstractmethod
    def send_newsletter(self, subject, recipients): ...

    @abstractmethod
    def alert_low_stock(self, product_id, units): ...


class ConsoleNotifier(NotificationCenter):
    """For local work: prints to the screen instead of sending emails."""

    def send_confirmation(self, order):
        print(f"[Simulated email] Order {order.id} confirmed")

    def send_newsletter(self, subject, recipients):
        raise NotImplementedError("Not used in orders")

    def alert_low_stock(self, product_id, units):
        raise NotImplementedError("Not used in orders")

The orders module only needs send_confirmation, but it depends on an interface with three methods. The consequences:

  • Any alternative implementation has to fill in methods it does not care about. The methods that raise NotImplementedError are, in addition, a violation of the Liskov principle.
  • If the way newsletters are sent changes, an interface that orders depends on changes, even though orders has nothing to do with newsletters.

The Refactoring

class Notifier(ABC):
    @abstractmethod
    def send_confirmation(self, order):
        """Tells the customer that their order is confirmed."""


class CampaignBroadcaster(ABC):
    @abstractmethod
    def send_newsletter(self, subject, recipients): ...


class StockAlerter(ABC):
    @abstractmethod
    def alert_low_stock(self, product_id, units): ...


class ConsoleNotifier(Notifier):
    def send_confirmation(self, order):
        print(f"[Simulated email] To {order.customer_email}: "
              f"order {order.id} confirmed, total €{order.total:.2f}")


order = Order(id=1042, customer_email="[email protected]",
              amount=45.0, shipping_cost=4.95)
ConsoleNotifier().send_confirmation(order)

Output:

[Simulated email] To [email protected]: order 1042 confirmed, total €49.95

Explanation:

  • Each interface corresponds to one client: Notifier to orders, CampaignBroadcaster to marketing campaigns, and StockAlerter to inventory.
  • ConsoleNotifier implements only what it needs. There are no more filler methods.
  • The same class can implement several interfaces. The real email service can inherit from all three, and each module will see it only through its own.

When It Is Not Worth It

  • When the interface has a single client and a single implementation. Splitting it adds nothing.
  • When the methods are always used together. find and save belong to the same repository interface: separating them would be fragmenting for the sake of it.

D: Dependency Inversion Principle

Statement. High-level modules should not depend on low-level modules: both should depend on abstractions. And abstractions should not depend on details; details should depend on abstractions.

In plain language. High-level code is the code that contains the business rules, such as confirming an order. Low-level code is the code that deals with technical details, such as calling PagoRaíz. The principle says that the business rules should not know the technical details. Instead, they declare what they need through an interface, and the details adapt to it.

The Code That Violates It

class OrderService:
    def __init__(self):
        self._repository = PostgresOrderRepository()
        self._gateway = PagoRaizGateway()      # direct dependency on a detail
        self._notifier = SmtpNotifier()

After applying single responsibility, the code is split up, but OrderService is still tied to PagoRaíz. You cannot confirm an order without making a real charge, or switch gateways without modifying this class.

The Refactoring

@dataclass
class ChargeResult:
    accepted: bool
    transaction_id: str = ""


class PaymentGateway(ABC):
    @abstractmethod
    def charge(self, reference, amount):
        """Charges the amount in euros and returns a ChargeResult."""


class PagoRaizGateway(PaymentGateway):
    def __init__(self, key):
        self._key = key

    def charge(self, reference, amount):
        response = requests.post(
            "https://api.pagoraiz.example/v1/charges",
            json={"amount_cents": round(amount * 100), "reference": reference},
            headers={"Authorization": self._key},
        )
        data = response.json()
        return ChargeResult(data["status"] == "AUTHORIZED", data.get("charge_id", ""))


class SimulatedGateway(PaymentGateway):
    def charge(self, reference, amount):
        print(f"[Simulated charge] {reference}: €{amount:.2f}")
        return ChargeResult(accepted=True, transaction_id="SIM-0001")


class OrderService:
    def __init__(self, repository, gateway, notifier):
        self._repository = repository
        self._gateway = gateway
        self._notifier = notifier

Explanation:

  • PaymentGateway is the abstraction. It is written in the store's vocabulary, with a charge method that receives euros, and not in PagoRaíz's, which works in cents.
  • ChargeResult is the response, also in the store's own terms. The rest of the store never sees the data as PagoRaíz returns it.
  • PagoRaizGateway is the detail: it implements the abstraction and does the translation.
  • SimulatedGateway is another detail, useful for local work without making real charges.
  • OrderService no longer creates its collaborators: it receives them in the constructor. It only knows the interfaces. The confirm method does not change.

Why is it called inversion? Before, the dependency arrow went from the business to the detail. Now it goes from the detail to the abstraction:

flowchart LR
    subgraph before["Before"]
        s1["OrderService"] --> p1["PagoRaizGateway"]
    end
    subgraph after["After"]
        s2["OrderService"] --> i2["PaymentGateway - interface"]
        p2["PagoRaizGateway"] --> i2
        p3["SimulatedGateway"] --> i2
    end

Here we have applied the principle to one class. Its true reach appears when it is applied to whole modules. We will develop that in the last lesson of this module.

When It Is Not Worth It

  • With stable dependencies, such as the Python standard library. Nobody needs an interface to add dates.
  • With internal collaborators that are small and have no external effects. It pays to abstract what is external, slow, paid, or changing: gateways, databases, email.

Summary Table

Principle Idea in one sentence Symptom that it is violated Example at Verdalia
Single responsibility A single reason to change Huge classes; names like “manager” OrderManager split into four classes
Open-closed Extend without modifying if chains by type that grow with every variant ShippingMethod and one class per method
Liskov substitution Subclasses honor the base's contract NotImplementedError; isinstance checks BulkyShipping leaves the hierarchy
Interface segregation Small interfaces, one per client Filler methods in the implementations Notifier, CampaignBroadcaster, StockAlerter
Dependency inversion The business depends on abstractions Business classes that create connections or HTTP clients PaymentGateway between orders and PagoRaíz

The five principles reinforce one another. Single responsibility produces small pieces; interface segregation and dependency inversion define how they connect; the open-closed principle and Liskov's guarantee that pieces can be added and swapped safely.

SOLID at Architecture Scale

The principles were born with classes in mind, but the same ideas work with larger pieces:

Principle At the scale of modules and services
Single responsibility Each module serves one business area. It is the criterion ADR-001 used to define the seven modules
Open-closed New capabilities, such as the “Plant of the Month” subscription, can be added as a new module, without reopening the existing ones
Liskov substitution Two implementations of the same contract are interchangeable: PagoRaíz could be replaced by another gateway without orders noticing
Interface segregation A module's public interface offers specific operations for each client, not general access to everything
Dependency inversion Business modules do not depend on infrastructure: database, email, and external services

This correspondence explains why we devote a whole module to code design in an architecture course: an architecture is, to a large extent, the application of these principles at scale.

Common Mistakes and Tips

  • Applying all five principles to all the code. The result is a design with more interfaces than logic. Apply them where change hurts: at Verdalia, orders, shipping, and payments.
  • Confusing single responsibility with tiny classes. The criterion is the reason to change, not the number of lines.
  • Inheriting to reuse code. Inheriting means accepting the complete contract of the base class. If you only want to reuse one method, inheritance is not the right tool.
  • Systematically creating an interface for every class. An interface with a single implementation, and no prospect of another, is just one more file.
  • Naming the abstraction after the vendor. An interface called PagoRaizInterface, with methods copied from PagoRaíz's, inverts nothing. The abstraction should express what the business needs.
  • Refactoring without a safety net. Reorganizing code without tests is risky. As long as Verdalia has no automated tests, Íker moves in small steps and checks each one by hand. The first tests will arrive at the end of this module.
  • Practical tip. Use the principles as questions, not as rules: who can request that this change? What would I have to touch to add a variant? What does this class need to know about the others?

Exercises

Exercise 1: Identify the Principle

State which principle is violated in each case:

  1. The Catalog class searches for products, generates the file for the price comparison site, and resizes images.
  2. The apply_discount function has an if branch for each campaign of the year, and with each new campaign another one is added.
  3. The SalesReport class creates a PostgreSQL connection in its constructor with psycopg2.connect.
  4. The GiftCard class inherits from Product, but its deduct_stock method raises an error, because a gift card has no stock.

Exercise 2: Add a Shipping Method

Andrés suggests that customers in Valencia be able to pick up their order at the warehouse, at no cost. Write the corresponding class. Then check with the shipping_options function that it complies with the Liskov substitution principle.

Solutions

Solution to Exercise 1

  1. Single responsibility. Three reasons to change: the searches, the format the comparison site requires, and image processing.
  2. Open-closed. Each variant forces a modification of existing code.
  3. Dependency inversion. A business class directly creates an infrastructure detail.
  4. Liskov substitution. The subclass does not honor the base's contract. The solution involves revising the hierarchy: not all products have stock, so that operation should not be in Product, but in a more specific type, such as a physical product.

Solution to Exercise 2

class WarehousePickup(ShippingMethod):
    code = "pickup"
    name = "Pickup at the Valencia warehouse"

    def calculate_cost(self, amount):
        return 0.0


print(shipping_options(45.0, METHODS + [WarehousePickup()]))

Output:

[('Standard shipping (48-72 hours)', 4.95), ('Express shipping (24 hours)', 8.9), ('Economy shipping (5-7 days)', 2.95), ('Pickup at the Valencia warehouse', 0.0)]

The class honors the contract: it accepts any amount, always returns a number greater than or equal to zero, and raises no errors. shipping_options works without knowing it exists.

Common mistake: adding an extra parameter to calculate_cost, such as the postal code, to check that the customer is in Valencia. That would change the method's signature and break substitution. If availability depends on the customer, it is a different responsibility, which should be added to the contract of all the methods.

Conclusion

In this lesson you have met the five SOLID principles and seen them act on Verdalia's code. With single responsibility, OrderManager has been split into classes that change for a single reason. With the open-closed principle, shipping methods have become classes that are added without touching the existing ones, a direct step toward scenario QS-5. The Liskov principle has kept a false shipping method from breaking the cart, interface segregation has given each module an interface tailored to it, and dependency inversion has separated orders from PagoRaíz. You have also seen that none of them is free and that applying them without need is another way of complicating the code.

SOLID does not exhaust the criteria of good design. Still pending, for instance, is the problem that started it all: the shipping cost calculation is still copied in the email template. Duplication, simplicity, and not building what nobody asked for are the subject of the next lesson: “Software Design Principles: DRY, KISS, YAGNI, and Separation of Concerns.”

© Copyright 2026. All rights reserved