The SOLID principles from the previous lesson help design classes, but they are not the only criteria of good design. There is another set of principles, more general and older, that apply to any code: from an email template to a whole system. In this lesson we will look at seven. With them, Íker will finally remove the last copy of the shipping cost calculation and tidy up the view_product function we met in Module 1. We will also see something the textbooks tend to keep quiet about: these principles clash with one another, and applying them well takes judgment.

DRY: Don't Repeat Yourself

DRY stands for “don't repeat yourself.” The principle says that every piece of knowledge should have a single representation within the system.

The key word is knowledge. The principle is not about similar-looking lines of code, but about business rules, decisions, and data. “Standard shipping costs €4.95 and is free for orders over €60” is a piece of knowledge. If it is written in three places, sooner or later the three versions will stop agreeing. At Verdalia it happened in June, and the emails showed wrong amounts for eight days.

The Case of the Shipping Costs

Let's review the state of the three copies:

Copy Where it was How it was removed
Cart utils.py The shipping module was created, in the lesson on coupling and cohesion
Order confirmation OrderManager.confirm_order OrderService calls the shipping module, in the lesson on SOLID
Confirmation email The email template Pending

The template is written in Jinja, the template language Flask uses. Instructions go between {% %} and the values displayed, between {{ }}:

<!-- templates/confirmation_email.html (before) -->
{% if order.shipping_method == "express" %}
  {% set cost = 8.90 %}
{% elif order.amount > 60 %}
  {% set cost = 0 %}
{% else %}
  {% set cost = 4.95 %}
{% endif %}
<p>Shipping cost: €{{ cost }}</p>
<p>Total: €{{ order.amount + cost }}</p>

The template recalculates what was already calculated when the order was confirmed. The problem is twofold: the rule is duplicated and, besides, the email does not show what was charged, but what results from applying the rule at the moment of sending it.

The solution is to calculate once and store the result. Remember that, since the previous lesson, OrderService.confirm records the cost on the order itself. Íker adds a shipping_cost column to the orders table to keep it, and the template simply displays it:

<!-- templates/confirmation_email.html (after) -->
<p>Shipping cost: €{{ order.shipping_cost }}</p>
<p>Total: €{{ order.total }}</p>

To check the result, Íker searches the whole codebase for the strings 4.95 and > 60. They appear in only one file: verdalia/shipping/methods.py. The rule finally lives in a single place.

Accidental Duplication and Premature Abstraction

Not everything that looks alike is a duplication. In the store there are two rules with the same number:

# Before: a shared constant because the value happens to match
STOCK_THRESHOLD = 5


def stock_notice(stock):                     # catalog: notice to the customer
    return "Last units" if stock < STOCK_THRESHOLD else ""


def needs_restock(stock):                    # inventory: alert to the warehouse
    return stock < STOCK_THRESHOLD
# After: two different pieces of knowledge, two constants
LAST_UNITS_THRESHOLD = 5        # commercial decision, in the catalog module
RESTOCK_THRESHOLD = 5           # warehouse decision, in the inventory module

Explanation:

  • The two rules are 5 by coincidence. They answer to different decisions, made by different people for different reasons.
  • With the shared constant, the day Andrés raises the “Last units” notice to 10, he will unintentionally change the moment at which the warehouse restocks.
  • This is accidental duplication: the text matches, but the knowledge is different. Unifying it creates a coupling between catalog and inventory that did not exist before.

The opposite mistake to duplicating is premature abstraction: creating a generic function, full of parameters, to serve two cases that only look alike on the outside. A duplication is easy to fix; a bad abstraction, which several modules already depend on, is much more expensive to undo.

Two questions help you decide:

  • Will they always change together? If the answer is yes, it is the same knowledge and should be unified. If they can change separately, they are two.
  • Is this the third time? The so-called rule of three advises tolerating the second copy and abstracting when the third appears. By then you know better what they have in common.

The rule of three applies to similar code whose relationship is doubtful. An identical business rule, such as the shipping cost one, should be unified the first time.

KISS: Keep It Simple

KISS is an acronym that can be read as “keep it simple.” The principle says that, between two solutions that solve the problem, the simpler one should be preferred.

Simple does not mean easy to write or short. It means having few concepts, few paths, and few surprises. A good measure is how long it takes someone else to understand it.

# Before: first version of the standard rate
import operator

RULES = [
    {"field": "amount", "operator": "gt", "value": 60.0, "cost": 0.0},
    {"field": "amount", "operator": "le", "value": 60.0, "cost": 4.95},
]
OPERATORS = {"gt": operator.gt, "le": operator.le}


def standard_cost(data):
    for rule in RULES:
        compare = OPERATORS[rule["operator"]]
        if compare(data[rule["field"]], rule["value"]):
            return rule["cost"]
    return None
# After
def standard_cost(amount):
    return 0.0 if amount > FREE_SHIPPING_THRESHOLD else 4.95

Explanation:

  • The first version, which Íker wrote two years ago, is a small rules engine: a list of conditions described as data and a loop that evaluates them. It works, but to understand it you need to know the operator module, the format of the rules, and the order in which they are evaluated.
  • It returns None if no rule matches, so the caller has to remember to check for it.
  • The second version does the same thing in one line that reads like the business sentence.
  • The engine was written on the assumption that one day there would be many rules. In two years, there were never more than two.

YAGNI: You Aren't Gonna Need It

YAGNI stands for “you aren't gonna need it.” The principle says that a feature should not be built until it is actually needed.

What is built just in case has four costs: writing it, testing it, maintaining it, and forcing everyone who reads the code to understand it. And it has one risk: when the need really arrives, it rarely matches what was imagined.

# Before: parameters for needs nobody has asked for
def calculate_shipping_cost(amount, method="standard", country="ES", currency="EUR",
                            weight_kg=None, coupon=None):
    if country != "ES":
        raise NotImplementedError("International shipping: pending")
    if currency != "EUR":
        raise NotImplementedError("Other currencies: pending")
    ...
# After: what the store needs today
def calculate_shipping_cost(amount, method="standard"):
    ...

Explanation:

  • Verdalia only ships within Spain and charges in euros. The country, currency, weight_kg, and coupon parameters do nothing, but everyone who calls the function wonders whether they should fill them in.
  • If one day shipping opens up to Portugal, a lot more than a signature will have to be redesigned. The empty parameter does not get that work done in advance.

The Shipping Rules Panel

In the last lesson of Module 1 we saw the trade-off between simplicity and flexibility with a real case: the shipping rules could be written in the code, with 1 day of work, or managed from a configurable panel, with 3 weeks. YAGNI provides the criterion for deciding: evidence.

Question Answer at Verdalia
Who has asked for the panel? Nobody. Andrés wants to be able to change the rules, not a panel
How often do the rules change? 2 times in the last 12 months
What does a change cost with the rules in the code? Modifying a value in the shipping module and deploying
Is the decision reversible? Yes. With the rules gathered in one module, adding the panel later does not require redoing anything

The decision is to keep the rules in the code. It will be reviewed if changes become more frequent than once a month.

An important nuance: YAGNI refers to features, not to design quality. Not building the panel is YAGNI. Leaving the rule copied in three places “because it will get tidied up eventually” is not: it is technical debt.

Separation of Concerns

The principle of separation of concerns says that a program should be divided into parts, so that each one deals with a single aspect of the problem. Edsger Dijkstra formulated it in 1974.

It resembles the single responsibility principle, but it is more general. That one refers to classes and reasons to change. This one applies at any scale and focuses on the kind of work: fetching data, deciding, and presenting are tasks of a different nature.

The clearest example is the view_product function, which in Module 1 mixed a SQL query, two business rules, and the construction of the page. This is what it looks like once separated:

# Data access: knows SQL, knows nothing about rules or pages
def find_product(connection, product_id):
    cursor = connection.cursor()
    cursor.execute(
        "SELECT name, price, stock FROM products WHERE id = %s",
        (product_id,),
    )
    name, price, stock = cursor.fetchone()
    return {"name": name, "price": float(price), "stock": stock}


# Business logic: knows the rules, knows nothing about where the data comes from
VAT = 0.21
LAST_UNITS_THRESHOLD = 5


def price_with_vat(price):
    return round(price * (1 + VAT), 2)


def stock_notice(stock):
    return "Last units" if stock < LAST_UNITS_THRESHOLD else ""


# Presentation: knows HTML, knows nothing about rules
def product_page(name, final_price, notice):
    return f"<h1>{name}</h1><p>€{final_price}</p><p>{notice}</p>"


# Coordination: the Flask function only wires the pieces together
@app.route("/product/<int:product_id>")
def view_product(product_id):
    product = find_product(get_connection(), product_id)
    return product_page(
        product["name"],
        price_with_vat(product["price"]),
        stock_notice(product["stock"]),
    )

The division looks like this:

flowchart LR
    route["view_product - coordination"] --> data["find_product - data access"]
    route --> rules["price_with_vat and stock_notice - business logic"]
    route --> view["product_page - presentation"]
    data --> db[("Database")]

The business and presentation functions can now run without a database and without Flask:

print(price_with_vat(6.50))
print(stock_notice(3))
print(product_page("Lavender", price_with_vat(6.50), stock_notice(3)))

Output:

7.87
Last units
<h1>Lavender</h1><p>€7.87</p><p>Last units</p>

Explanation:

  • find_product receives the connection as a parameter instead of creating it, and returns a dictionary with simple data. It is the only function that knows the products table.
  • price_with_vat and stock_notice are pure functions: their result depends only on what they receive. That is why they are so easy to check.
  • product_page receives the values already calculated. If the page design changes tomorrow, there is no risk of breaking the price calculation.
  • view_product has been reduced to coordinating. get_connection is a helper function that hands over the database connection.
  • When the business asks to show “Last units” in the cart, calling stock_notice will be enough. That was the exercise we set in Module 1.

When this separation is applied systematically to the whole application, the result is a layered architecture. We will study it in the first lesson of Module 3.

Law of Demeter, or the Principle of Least Knowledge

The Law of Demeter says that an object should only talk to its immediate collaborators, and not to the collaborators of its collaborators. It is summed up in one sentence: “don't talk to strangers.”

# Before: shipping walks through the cart's internal structure
def delivery_time(cart):
    if cart.customer.address.province == "Valencia":
        return "24 hours"
    return "48-72 hours"
# After, option 1: ask the immediate collaborator
def delivery_time(cart):
    if cart.delivery_province() == "Valencia":
        return "24 hours"
    return "48-72 hours"


# After, option 2: receive only the data needed
def delivery_time(province):
    return "24 hours" if province == "Valencia" else "48-72 hours"

Explanation:

  • In the first version, the function knows three things that are not its own: that the cart has a customer, that the customer has an address, and that the address has a province. If one day shipping to an address other than the customer's is allowed, this function will fail.
  • In option 1, the cart offers a method that answers the question. How it finds out is its own business.
  • Option 2 is even better when it is possible: the function receives a simple value. That is the data coupling we saw in the first lesson of the module.

The law is not about counting dots. An expression like text.strip().lower() chains calls, but each one returns a new string and nobody's internals are entered. The warning sign is going through objects from different modules to reach a piece of data.

Composition Over Inheritance

This principle recommends that, to combine behaviors, you prefer an object that has other objects, which is called composition, over one that is a variant of another, which is inheritance.

# Before: one subclass per combination
class Order: ...
class ExpressOrder(Order): ...
class GiftOrder(Order): ...
class ExpressGiftOrder(ExpressOrder, GiftOrder): ...
# With economy shipping: EconomyOrder, EconomyGiftOrder...
# After: the order has a shipping method and a list of extras
@dataclass
class GiftWrap:
    name: str = "Gift wrap"
    cost: float = 2.50


@dataclass
class Order:
    amount: float
    shipping_method: object
    extras: list = field(default_factory=list)

    @property
    def total(self):
        cost = self.shipping_method.calculate_cost(self.amount)
        extras_cost = sum(extra.cost for extra in self.extras)
        return round(self.amount + cost + extras_cost, 2)


print(Order(45.0, StandardShipping()).total)
print(Order(45.0, ExpressShipping(), [GiftWrap()]).total)

Output:

49.95
56.4

Explanation:

  • With inheritance, each combination needs its own class. Three shipping methods and two optional extras add up to twelve combinations.
  • With composition, the order contains a ShippingMethod object, from those defined in the previous lesson, and a list of extras. Three methods and two extras are five small classes, which combine freely.
  • field(default_factory=list) indicates that, if no extras are passed, each order starts with its own empty list.
  • Gift wrap is a hypothetical example. The day it is offered, the Order class will not have to be touched.
  • This Order is a reduced version for the example. The real class keeps the fields we saw in the previous lesson.

Inheritance remains appropriate when there is a genuine “is a kind of” relationship and the Liskov substitution principle holds, as between ExpressShipping and ShippingMethod.

Principle of Least Astonishment

The principle of least astonishment says that code should behave the way whoever uses it expects. If a function does something its name does not announce, sooner or later someone will use it wrongly.

# Before
def get_shipping_cost(order):
    cost = calculate_shipping_cost(order.amount, order.shipping_method)
    order.shipping_cost = cost
    repository.save(order)            # surprise: a function that "gets" and saves
    if cost == 0:
        return "FREE"                 # surprise: sometimes it returns a string
    return cost
# After: the calculation always returns a number and modifies nothing
cost = calculate_shipping_cost(order.amount, order.shipping_method)


# Converting to text is a presentation matter
def cost_text(cost):
    return "Free" if cost == 0 else f"€{cost:.2f}"


print(cost_text(0.0), "/", cost_text(4.95))

Output:

Free / €4.95

Explanation:

  • The original function has two surprises. Its name suggests a query, but it modifies the order and saves it. And it returns a number or a string depending on the case, so a sum like amount + get_shipping_cost(order) fails only with free-shipping orders.
  • In the corrected version, calculating, saving, and presenting are three visible steps, each with a name that says what it does.
Recommendation Example
The name describes everything the function does calculate_, find_, and get_ do not modify; save_ and send_ do
The result is always of the same type Always a number, never a number or a string
Units are consistent Always euros; the conversion to cents happens at a single point
Errors are reported as errors Raise ValueError instead of returning None or -1

Tensions Between Principles and How to Resolve Them

Applied without measure, the principles contradict one another:

Tension How it shows up
DRY vs. KISS To remove a repetition, an abstraction is created that is harder to understand than the two copies
DRY vs. low coupling Sharing code between two modules ties them together: a change intended for one affects the other
YAGNI vs. the open-closed principle Preparing extension points is, in part, building for the future
Separation of concerns vs. KISS Splitting a trivial operation into five pieces makes it harder to follow

There is no formula, but there are questions that order the decision:

  1. Which quality scenario is at stake? At Verdalia, the priority for the code is QS-5. A design that reduces the number of modules affected by a change takes precedence.
  2. Is it the same knowledge? If two fragments always change together, DRY wins. If they merely look alike, simplicity wins.
  3. Is there evidence? A variation that has already happened three times deserves an extension point. An imagined variation does not.
  4. How much does changing your mind cost? If the decision is reversible, choose the simple option and correct it when there is data.
  5. Would a newcomer understand it? If the answer is no, the solution needs to be simpler, however correct it may be.

The shipping methods illustrate the third question. Íker created one class per method because the variation was real: two existing methods, a third one announced, and a history of rate changes. On the other hand, he did not build the panel, because nobody had asked for it.

Common Mistakes and Tips

  • Reading DRY as “looking alike is forbidden.” Unifying two fragments that match by chance creates coupling where there was none.
  • Using YAGNI as an excuse not to tidy up. The principle refers to features nobody asked for, not to tests or to clean code.
  • Confusing simple with quick to write. Copying and pasting is quick, but the result is not simple: there is more code to maintain.
  • Generalizing at the first opportunity. With a single case you cannot tell what is essential and what is incidental.
  • Hiding side effects in query functions. A function that appears to read and also writes is a guaranteed source of errors.
  • Leaving calculations in templates. A template should display data that has already been calculated. Any rule written in it is invisible to the rest of the code.
  • Practical tip. When two principles clash, write both versions. Seeing the actual code settles many theoretical arguments.

Exercises

Exercise 1: Identify the Principle

State which principle is violated in each case:

  1. The function find_customer(email) also records the customer's last login date.
  2. The VAT rate, 0.21, is written in 14 files.
  3. Íker proposes that the catalog support several languages “in case we sell abroad someday,” although there is no plan to do so.
  4. The notifications code contains order.cart.customer.preferences.language.

Exercise 2: A Notice in the Cart

Andrés wants the cart to show how much is left to qualify for free shipping. A colleague proposes writing remaining = 60 - amount in the cart. Explain which principle it violates and write a solution. Keep in mind that shipping is free for orders of more than €60.

Exercise 3: Resolve a Tension

The functions that generate the confirmation email and the shipping notice email have eight nearly identical lines, which build the header with the logo and the greeting. Íker is torn between leaving them as they are or creating a shared function. What would you recommend?

Solutions

Solution to Exercise 1

  1. Least astonishment. A function called find_ should not modify anything.
  2. DRY. The VAT rate is a piece of knowledge and should be in one place.
  3. YAGNI. It is a feature with no current need, which makes the whole catalog more expensive.
  4. Law of Demeter. Notifications walks through four objects from other modules. It should receive the language as data.

Solution to Exercise 2

It violates DRY: the number 60 and the free-shipping rule would be written in a second place. The rule belongs to the shipping module, which should offer the answer in its public interface:

# verdalia/shipping/methods.py
def amount_left_for_free_shipping(amount):
    """Euros still needed for standard shipping to be free (0 if it already is)."""
    if amount > FREE_SHIPPING_THRESHOLD:
        return 0.0
    return round(FREE_SHIPPING_THRESHOLD - amount + 0.01, 2)


# verdalia/cart
def free_shipping_message(amount):
    remaining = amount_left_for_free_shipping(amount)
    if remaining == 0:
        return "Your order qualifies for free standard shipping"
    return f"Add €{remaining:.2f} and standard shipping will be free"


for amount in (19.80, 60.00, 63.00):
    print(f"{amount:.2f}: {free_shipping_message(amount)}")

Output:

19.80: Add €40.21 and standard shipping will be free
60.00: Add €0.01 and standard shipping will be free
63.00: Your order qualifies for free standard shipping

Notice the case of exactly €60. With the colleague's formula, the cart would have shown that €0 was left, while the order kept paying €4.95. That is the kind of discrepancy that appears when a rule is written twice. The division also respects separation of concerns: shipping calculates and the cart writes the message.

Solution to Exercise 3

It helps to apply the lesson's questions. Is it the same knowledge? Yes: the corporate header is a single decision, and if the logo changes, it will change in every email. Does the code get more complicated when unified? No: an email_header(customer_name) function is easy to understand. Does it create coupling between modules? No, because both functions belong to the notifications module.

The recommendation is to unify. Here DRY and KISS do not clash. It would be different if, to unify, parameters such as with_logo or greeting_type had to be added, because that would indicate that the headers are not the same and that the abstraction is being forced.

Conclusion

In this lesson you have met seven general design principles. DRY asks that every piece of knowledge live in one place, without confusing real duplication with accidental duplication. KISS asks you to choose the simplest solution that works, and YAGNI, not to build what nobody has asked for. Separation of concerns distinguishes between fetching data, deciding, and presenting. The Law of Demeter limits what each piece knows about the others, composition avoids hierarchies that grow out of control, and the principle of least astonishment demands that code do what it appears to do. You have also seen that they clash with one another and that the clashes are resolved with concrete questions, not with dogmas.

At Verdalia, the shipping cost calculation now lives in a single place, the email shows what was really charged, and view_product has been separated into pieces that can be checked without a database.

Over these three lessons several recurring solutions have appeared: one class per variant, an interface of your own in front of an external service, objects that combine. They are not Íker's inventions. They are well-known solutions, with names of their own, that the profession has been cataloging. We will study them in the next lesson: “Design Patterns.”

© Copyright 2026. All rights reserved