The previous module ended with a decision, ADR-001, and with a question: what exactly does modularizing mean, and how do you know whether a module is well delimited? In this lesson we go into the store's code for the first time to answer it. You will learn what a module is, how the quality of a division is measured with two concepts, cohesion and coupling, and how a module is protected by a public interface. These are the ideas that the whole of Module 2 rests on and, in fact, any architecture: from a single function to a system of a hundred services.
What a Module Is and What Modularizing Means
A module is a part of the system that groups code and data related to a single responsibility, that is used through a defined interface, and whose internals can change without the rest noticing.
The definition has three ingredients, and all three are necessary:
| Ingredient | What it means | What happens if it is missing |
|---|---|---|
| One responsibility | Everything it contains serves the same purpose | The module is a grab bag |
| An interface | There is an explicit list of what others may use | Others use anything at all, and everything ends up tied together |
| Hidden internals | Whatever is not in the interface is private | Any internal change breaks whoever depended on it |
A word about vocabulary. In Python, a .py file is called a module and a folder with an __init__.py file is called a package. In this course we use “module” in the architectural sense: each of the seven functional areas of ADR-001, that is, catalog, cart, orders, payments, inventory, shipping, and notifications. In the code, each module will be a Python package.
Modularizing is reorganizing a system into modules. It does not consist of spreading files across folders: moving the mess into seven folders produces seven messy folders. Modularizing is deciding where the boundaries are, what crosses each boundary, and what stays inside.
A good division pursues three benefits:
- Understanding in parts. Nobody can hold 55,000 lines in their head, but they can hold a 3,000-line module and the interfaces of the others.
- Changing in parts. A change in shipping should touch only the shipping module. That is, literally, scenario QS-5.
- Testing in parts. A module with few dependencies can be checked without starting up the whole system.
To know whether a division is good we need to measure it. The two classic measures are cohesion, which looks inward at each module, and coupling, which looks outward.
Cohesion: What the Pieces of a Module Have in Common
Cohesion is the degree to which the elements of a module belong together. A module is highly cohesive when everything it contains contributes to the same task. You want high cohesion.
A quick test: try to describe the module in one sentence without using the word “and.” “Calculates shipping costs” passes the test. “Formats prices, sends emails, and deducts stock” does not.
Not all ways of grouping are equal. The traditional classification distinguishes seven types, ordered from worst to best:
| Type of cohesion | The elements are together because... | Example in a store | Rating |
|---|---|---|---|
| Coincidental | No reason: they just landed there | utils.py with prices, emails, and stock |
Very bad |
| Logical | They do things of the same category, and a parameter picks which | export(kind), which generates a label, a listing, or an accounting report |
Bad |
| Temporal | They run at the same moment | startup.py: opens the connection, loads the configuration, and deletes temp files |
Bad |
| Procedural | They run in a fixed order, on different data | daily_close(): backs up the database, empties old carts, and sends a report |
Fair |
| Communicational | They work on the same data | Functions that, from an order, print the invoice and compute statistics | Acceptable |
| Sequential | The output of one is the input of the next | Reading a supplier's price list, validating it, and loading it into the catalog | Good |
| Functional | All of them contribute to a single well-defined task | A module that only calculates shipping costs | The best |
A few observations to interpret the table:
- The first three types share one defect: the elements change for different reasons. In
utils.py, a change to the emails and another to the stock force you to touch the same file, even though they have nothing to do with each other. - Logical cohesion usually gives itself away through a parameter that selects the behavior. If a function starts with
if kind == ...and each branch does something unrelated to the others, they are really several functions disguised as one. - The scale is not an exam. You do not need to classify every file precisely. What matters is spotting the clearly bad cases and knowing which direction to improve in.
Coupling: How Much a Module Knows About the Others
Coupling is the degree to which a module depends on others. Two modules are tightly coupled when a change in one forces a change in the other. You want low coupling.
Low does not mean none. A module that relates to nobody is useless: the cart needs the catalog, and orders need payments. The useful question is not whether there are dependencies, but how many there are and of what kind. From worst to best:
| Type of coupling | What it consists of | Example in a store | Rating |
|---|---|---|---|
| Content | One module uses or modifies the internals of another | The payments code changes an order's status by writing to the orders table |
Very bad |
| Common, or shared data | Several modules read and write the same global data | A global connection variable; a table queried by five areas |
Bad |
| Control | One module tells another how to behave through a flag | A formatted=True parameter that changes what the function returns |
Fair |
| Stamp, or structure | A whole structure is passed when only part of it is needed | Passing the complete order to a function that only needs the amount | Acceptable |
| Data | Only the simple data that is needed is passed | calculate_shipping_cost(amount, method) |
Good |
| Message | A module announces something without knowing who receives it | Announcing “order confirmed” so that whoever is interested reacts | The lowest |
Three of them deserve a closer look:
- Content coupling and common coupling are invisible. They do not show up in
importstatements. If the notifications code runs aSELECTon theorderstable, it depends on the orders module even though it does not import it. That is why renaming a column is so risky at Verdalia. - Stamp coupling looks harmless, but it has a cost. Whoever receives the whole order may end up using any field. Over time nobody knows what each function really needs.
- Message coupling is not free. In exchange for independence, the flow is harder to follow. We will apply it inside the application in the lesson “Design Patterns” and between components in Module 3.
Cohesion and coupling are related: when a module has little cohesion, its responsibilities are scattered or mixed, and the others need to reach into it through many places. The rule that sums up the lesson is: high cohesion within, low coupling between modules.
Afferent and Efferent Coupling
Beyond the type, the direction of each dependency matters. If the cart uses shipping, the dependency leaves the cart and enters shipping.
| Measure | What it counts | Question it answers |
|---|---|---|
| Efferent coupling: outgoing dependencies | How many modules this one depends on | How many changes elsewhere can break me? |
| Afferent coupling: incoming dependencies | How many modules depend on this one | How many can I break if I change? |
Combining both measures describes the role of each module:
| Incoming | Outgoing | Role | How to treat it |
|---|---|---|---|
| Many | Few | Stable base: many lean on it | Change its interface with great care; it should be simple and well tested |
| Few | Many | Coordinator: brings together the work of others | Can change freely, but suffers the changes of the others |
| Many | Many | Knot: everything goes through it | Warning sign; split it or reduce its dependencies |
| Few | Few | Isolated piece | No risk |
A practical recommendation follows: dependencies should point toward the most stable modules, the ones with the fewest reasons to change. That orders, which changes often, depends on shipping is reasonable. That shipping depends on orders is a bad sign.
Information Hiding: Public Interface and Internal Details
Information hiding is the principle by which each module hides its design decisions, especially the ones that may change, and shows only what is strictly necessary.
- The public interface is what the module promises: the functions it offers, what data they receive, and what they return. It should be small and change rarely.
- The internal details are everything else: how things are computed, which tables they are stored in, which helper functions exist. They should be free to change.
A useful comparison is a power outlet. The interface is the shape of the plug and the voltage. Whether the electricity comes from a solar plant or a hydroelectric one is an internal detail: it can change without replacing the lamp.
In Verdalia's shipping module, the interface will be the function that calculates the cost. The free-shipping threshold, the rates, and the way the calculation is organized will be internal details.
Python does not prevent access to a module's internals, but it offers conventions that everybody respects:
- A name that starts with an underscore, such as
_rates.pyor_FREE_SHIPPING_THRESHOLD, is private. - The package's
__init__.pyfile defines what is offered to the outside, and the__all__list declares it explicitly.
In a modular monolith there is one more rule, perhaps the most important: tables are internal details too. Each table belongs to a module, and the others request the data through its interface, never with a SQL query of their own. ADR-001 keeps a single database, but that does not mean all the code may read all of it.
Diagnosing Verdalia's Monolith
During the first week of work, Íker and Marta went through the code looking for five symptoms. This is what they found:
| Symptom | What they found | What it indicates |
|---|---|---|
| Grab-bag module | utils.py: 2,100 lines and 96 unrelated functions, imported from 47 files |
Coincidental cohesion |
| Code that reads other modules' tables | The orders table is queried with SQL from five of the seven areas |
Shared-data coupling |
| Code that writes to other modules' tables | The payments code directly modifies the status of orders | Content coupling |
| Global state | The connection variable, created in utils.py and used throughout the store |
Common coupling |
| Circular dependencies | 19 dependencies between areas, 6 of them mutual | Nothing can be changed or tested separately |
A circular dependency appears when A depends on B and B depends, directly or through others, on A. It is especially harmful because it turns the modules involved into a single one: you cannot understand, test, or change one without the other.
How to look for these symptoms in any codebase:
- Generic names. Files called
utils,common,misc,helpers, ormanagerare usually grab bags. - A file that changes with everything. If the same file shows up in almost every change in the repository history, it has too many responsibilities.
- Searching for table names. Searching for the text
FROM ordersacross the whole codebase reveals who reads that table. - Imports inside functions. In Python, an
importhidden inside a function is usually a workaround to dodge a circular dependency.
The diagram shows the dependencies between areas as they were. When there are arrows in both directions between two areas, the dependency is mutual:
flowchart LR
catalog["Catalog"] --> inventory["Inventory"]
inventory --> catalog
cart["Cart"] --> catalog
cart --> inventory
cart --> shipping["Shipping"]
shipping --> cart
orders["Orders"] --> cart
orders --> payments["Payments"]
payments --> orders
orders --> inventory
inventory --> orders
orders --> shipping
shipping --> orders
orders --> notifications["Notifications"]
notifications --> orders
payments --> notifications
inventory --> notifications
notifications --> shipping
notifications --> catalog
And this is the target they set themselves: the same seven areas, with fewer than half the dependencies and all of them in a single direction.
flowchart LR
orders["Orders"] --> cart["Cart"]
orders --> payments["Payments"]
orders --> inventory["Inventory"]
orders --> shipping["Shipping"]
orders --> notifications["Notifications"]
cart --> catalog["Catalog"]
cart --> shipping
catalog --> inventory
Before and After: From utils.py to the Shipping Module
Marta proposed starting with something small and painful: shipping costs. Of the three copies of the calculation, the one the cart uses lives in utils.py.
Before
# utils.py (excerpt: the real file has 2,100 lines)
import psycopg2
import config
# Global state: any file can use and modify it
connection = psycopg2.connect(
host="localhost", dbname="verdalia",
user="store", password=config.DB_PASSWORD,
)
def format_price(amount):
return f"€{amount:.2f}"
def cart_shipping_cost(cart_id, method="standard", formatted=False):
# Reads cart and catalog tables directly
cursor = connection.cursor()
cursor.execute(
"SELECT SUM(i.quantity * p.price) FROM cart_items i "
"JOIN products p ON p.id = i.product_id WHERE i.cart_id = %s",
(cart_id,),
)
amount = float(cursor.fetchone()[0])
if method == "express":
cost = 8.90
elif amount > 60:
cost = 0.0
else:
cost = 4.95
# The formatted flag changes the type of the returned value
if formatted:
return "Free" if cost == 0 else format_price(cost)
return cost
# ... and 94 more functions: stock, emails, dates, couponsExplanation:
- The file mixes price formatting, shipping costs, stock, emails, and coupons. That is coincidental cohesion: its functions change for different reasons.
connectionis a global variable. Every function depends on it without declaring so: common coupling.cart_shipping_costqueries thecart_itemsandproductstables. A shipping function knows the internal structure of the cart and the catalog: shared-data coupling.- The
formattedparameter makes the function sometimes return a number and sometimes a string: control coupling. - The business rules, which are the only thing that is really about shipping, take up six lines buried in the middle of everything else. And they cannot be tested without a running database.
After
The shipping module is created as a package with two files: __init__.py, which is its public interface, and _rates.py, which contains the internal details.
# verdalia/shipping/__init__.py
"""Shipping module: everything related to shipping methods and costs."""
from verdalia.shipping._rates import calculate_shipping_cost
__all__ = ["calculate_shipping_cost"]# verdalia/shipping/_rates.py
_FREE_SHIPPING_THRESHOLD = 60.0
def calculate_shipping_cost(amount, method="standard"):
"""Returns the shipping cost, in euros, of an order."""
if method == "standard":
if amount > _FREE_SHIPPING_THRESHOLD:
return 0.0
return 4.95
if method == "express":
return 8.90
raise ValueError(f"Unknown shipping method: {method}")And the cart, which is the one that knows its own items, calculates the amount and asks for the cost:
# verdalia/cart/__init__.py
from verdalia.shipping import calculate_shipping_cost
def cart_summary(items, method="standard"):
"""Calculates the amount, the shipping cost, and the total of a cart."""
amount = sum(item["price"] * item["quantity"] for item in items)
cost = calculate_shipping_cost(amount, method)
return {
"amount": amount,
"shipping_cost": cost,
"total": round(amount + cost, 2),
}A manual test:
from verdalia.cart import cart_summary
large_cart = [
{"product": "Potted olive tree", "price": 38.00, "quantity": 1},
{"product": "Clay pot", "price": 12.50, "quantity": 2},
]
small_cart = [{"product": "All-purpose potting soil", "price": 9.90, "quantity": 2}]
print(cart_summary(large_cart))
print(cart_summary(small_cart))
print(cart_summary(small_cart, method="express"))Output:
{'amount': 63.0, 'shipping_cost': 0.0, 'total': 63.0}
{'amount': 19.8, 'shipping_cost': 4.95, 'total': 24.75}
{'amount': 19.8, 'shipping_cost': 8.9, 'total': 28.7}Explanation:
__init__.pyimports the function from the internal file and publishes it. Whoever uses the module will writefrom verdalia.shipping import calculate_shipping_costand will not need to know that_rates.pyexists._FREE_SHIPPING_THRESHOLDstarts with an underscore: it is an internal detail. The current rules are standard shipping at €4.95, free for orders over €60, and express shipping at €8.90.calculate_shipping_costreceives two simple values and always returns a number. That is data coupling, the best of those that involve a direct call. It queries no table and uses no global variables.- If the method does not exist, the function raises an error instead of returning a made-up value.
cart_summarycalculates the amount from its own items. Each module takes care of its own data.- In this course we use ordinary floating-point numbers to keep the examples simple. In a real system, amounts are handled with the
Decimaltype, which avoids rounding errors.
| Aspect | Before | After |
|---|---|---|
| Cohesion | Coincidental | Functional |
| Coupling | Common, shared-data, and control | Data |
| Dependencies of the shipping rule | Database, configuration, tables from two areas | None |
| Testable without a database | No | Yes |
An important caveat: this step gives the rule a home, but it does not yet solve the whole problem. The other two copies of the calculation, the one in order confirmation and the one in the email template, are still where they were. We will deal with them in the lesson on DRY, KISS, and YAGNI. utils.py, for its part, does not disappear all at once: it is emptied function by function, as each one finds its module.
Measuring Dependencies with Python
Íker noted down which area uses which and expressed it as a dictionary. With a small program you can count the dependencies and detect cycles.
dependencies_before = {
"catalog": ["inventory"],
"cart": ["catalog", "inventory", "shipping"],
"orders": ["cart", "payments", "inventory", "shipping", "notifications"],
"payments": ["orders", "notifications"],
"inventory": ["catalog", "orders", "notifications"],
"shipping": ["orders", "cart"],
"notifications": ["orders", "shipping", "catalog"],
}
target_dependencies = {
"catalog": ["inventory"],
"cart": ["catalog", "shipping"],
"orders": ["cart", "payments", "inventory", "shipping", "notifications"],
"payments": [],
"inventory": [],
"shipping": [],
"notifications": [],
}Each key is a module, and its value is the list of modules it depends on. Both imports and reads of other modules' tables are included.
The two analysis functions are these:
def count_dependencies(dependencies):
"""Returns, for each module, how many dependencies leave it
(efferent) and how many arrive at it (afferent)."""
counts = {}
for module in dependencies:
counts[module] = {"outgoing": 0, "incoming": 0}
for module, used in dependencies.items():
counts[module]["outgoing"] = len(used)
for dependency in used:
counts[dependency]["incoming"] += 1
return counts
def find_cycle(dependencies):
"""Returns a list of modules that form a cycle,
or None if the dependency graph has none."""
visited = set()
def walk(module, path):
if module in path:
start = path.index(module)
return path[start:] + [module]
if module in visited:
return None
visited.add(module)
for dependency in dependencies[module]:
cycle = walk(dependency, path + [module])
if cycle:
return cycle
return None
for module in dependencies:
cycle = walk(module, [])
if cycle:
return cycle
return NoneExplanation:
count_dependenciesprepares a counter per module. Outgoing dependencies are the length of its list. Incoming ones are obtained by going through the others' lists and adding one to the module used.find_cyclefollows the arrows from each module and remembers the path taken. If it reaches a module that is already on the path, it has doubled back on itself: there is a cycle, and it returns the stretch that forms it.visitedavoids exploring the same thing twice.walkis a recursive function: it calls itself to advance along each dependency.
Finally, a function that presents the results:
def report(title, dependencies):
print(title)
for module, data in count_dependencies(dependencies).items():
print(f" {module:<15} outgoing: {data['outgoing']} incoming: {data['incoming']}")
total = sum(len(used) for used in dependencies.values())
print(f" Total: {total} Cycle: {find_cycle(dependencies)}")
report("BEFORE", dependencies_before)
report("TARGET", target_dependencies)Output:
BEFORE catalog outgoing: 1 incoming: 3 cart outgoing: 3 incoming: 2 orders outgoing: 5 incoming: 4 payments outgoing: 2 incoming: 1 inventory outgoing: 3 incoming: 3 shipping outgoing: 2 incoming: 3 notifications outgoing: 3 incoming: 3 Total: 19 Cycle: ['catalog', 'inventory', 'catalog'] TARGET catalog outgoing: 1 incoming: 1 cart outgoing: 2 incoming: 1 orders outgoing: 5 incoming: 0 payments outgoing: 0 incoming: 1 inventory outgoing: 0 incoming: 2 shipping outgoing: 0 incoming: 2 notifications outgoing: 0 incoming: 1 Total: 8 Cycle: None
Reading the results:
- Before, orders had 5 outgoing dependencies and 4 incoming ones: it was a knot. A change in orders could break four areas, and a change in any of five others could break orders. This explains why one in three deployments caused an incident.
- In the target, orders keeps its 5 outgoing dependencies but has no incoming ones. It is a coordinator: it brings together the work of the others, and nobody depends on it.
- Shipping, payments, inventory, and notifications become stable bases: they depend on nobody, so they can be understood and tested separately.
- The 19 dependencies drop to 8, and the cycles disappear.
The target is a blueprint, not a reality: getting there will take weeks. But now the team can repeat the measurement every month and check whether it is making progress.
Common Mistakes and Tips
- Confusing folders with modules. A folder without a public interface or protected internals is just a way of arranging files.
- Creating a “common” module for everything shared. That is
utils.pyunder another name. What is shared should be minimal and, where possible, belong to a module with its own responsibility. - Chasing zero coupling. It is impossible and not desirable. The goal is for dependencies to be few, explicit, and one-directional.
- Splitting by technical type instead of by area. One folder with all the models, another with all the queries, and another with all the screens forces you to touch all three on every change. Splitting by functional area keeps together what changes together.
- Forgetting the database. Two modules without a single import between them can be tightly coupled if they read the same table.
- Fixing a cycle with a late import. It hides the symptom and keeps the problem. A cycle is resolved by moving responsibilities or, as we will see in this module, by inverting a dependency.
- Practical tip. Before creating a module, write its public interface down on paper: what it offers and to whom. If it does not fit on half a page, the module does too much.
Exercises
Exercise 1: Classify
State the type of cohesion or coupling in each case and whether it is desirable:
- A file
nightly.pywith all the tasks that run at 3:00 a.m.: backups, cleanup of abandoned carts, and sending statistics. - The function
stock_notice(stock), which receives a number and returns the text of the notice. - The catalog code changes the
_price_cachevariable defined inside another file. - The function
generate(document, kind), which produces an invoice, a shipping label, or a gift voucher depending on the value ofkind. - The function
calculate_shipping_cost(order), which receives the complete order, with customer, items, and payments, and only uses the amount.
Exercise 2: One Dependency Too Many
Andrés wants to launch the “Plant of the Month” subscription. Íker plans a subscriptions module that will depend on catalog, payments, shipping, and notifications.
- Add it to
target_dependenciesand run the report. Do any cycles appear? - A colleague proposes that
shippingquerysubscriptionsto apply free shipping to subscribers. Add that dependency, repeat the report, and propose an alternative.
Exercise 3: Design a Public Interface
Design the public interface of the inventory module: list three to five functions it would offer and three details it would keep hidden. Remember that today stock is a column of the products table, which the catalog also uses.
Solutions
Solution to Exercise 1
| Case | Type | Desirable? |
|---|---|---|
1. nightly.py |
Temporal cohesion | No. Each task should live in its own module; the nightly file should only call them |
2. stock_notice |
Data coupling and functional cohesion | Yes |
3. Changing _price_cache |
Content coupling | No. It is the worst type: the internals of another module are modified |
4. generate(document, kind) |
Logical cohesion and control coupling | No. They are three different functions |
5. calculate_shipping_cost(order) |
Stamp coupling | Could be better. Passing the amount is enough |
Common mistake in case 1: thinking the file is unnecessary. It can exist as the entry point for the nightly tasks; what it must not contain is the logic of each one.
Solution to Exercise 2
exercise_dependencies = dict(target_dependencies)
exercise_dependencies["subscriptions"] = [
"catalog", "payments", "shipping", "notifications",
]
report("WITH SUBSCRIPTIONS", exercise_dependencies)
exercise_dependencies["shipping"] = ["subscriptions"]
report("WITH THE NEW DEPENDENCY", exercise_dependencies)Last line of each report:
The new module creates no cycles: it is a coordinator, with 4 outgoing dependencies and no incoming ones. The colleague's proposal does create one, and it also makes shipping, a stable base with 3 incoming dependencies, depend on a brand-new module that will change a lot.
The alternative is for shipping not to ask, but to receive the information. The caller already knows whether the customer is a subscriber, and can say so when requesting the calculation. That is data coupling, and the dependency keeps going in a single direction.
Solution to Exercise 3
One possible proposal:
| Public interface | Internal details |
|---|---|
available_stock(product_id) |
Which table and column the stock is stored in |
has_stock(product_id, units) |
How availability is computed: stock minus reserved units |
reserve(product_id, units) |
The threshold below which low stock is reported |
deduct(product_id, units) |
Notice that no function in the interface mentions tables or SQL. Thanks to that, the day stock moves to a table of its own, the catalog will not have to change: it will keep calling available_stock. The shared table is a hidden dependency that the interface lets you undo step by step.
Conclusion
In this lesson you have learned that a module is not a folder, but a responsibility with a public interface and hidden internals. You have seen the two measures of a good division: cohesion, which should be high and has seven degrees, from coincidental to functional; and coupling, which should be low and ranges from content to message coupling. You have also distinguished incoming dependencies from outgoing ones and confirmed that shared tables and global variables are dependencies even though they appear in no import.
At Verdalia, the diagnosis produced concrete figures: a 2,100-line utils.py, 19 dependencies between areas, and 6 of them mutual. The team has a blueprint of 8 dependencies without cycles and a first module, shipping, with a single-function interface.
Cohesion and coupling tell you whether a design is good, but not how to achieve it when writing a specific class. For that there are more specific principles. The five best known form an acronym, and with them Íker is going to face the most feared class in the store, OrderManager. We will see them in the next lesson: “SOLID Principles.”
