Blog

Principles of Modularity in Software Development

Modularity means splitting a program into parts that each do one job, hide how they do it, and talk to the rest of the code through a small, stable interface. The payoff is that you can change, test and reuse one part without reading or breaking the others. The principles that make it work are high cohesion, low coupling, information hiding and clear interfaces. This post explains each with a worked Python example, then covers the cost of overdoing it.

The core principles

High cohesion

Everything inside a module should belong together. A module called utils that holds date parsing, password hashing and a retry helper has low cohesion: nothing explains why those live together, so people add anything to it. A module that handles invoices, and only invoices, has high cohesion. A quick test is whether you can describe the module’s job in one sentence without using “and”.

Low coupling

Coupling is how much one module needs to know about another. If changing module A forces edits in B, C and D, they are tightly coupled. Common causes are reaching into another module’s internal data, sharing global variables, and creating concrete dependencies inside a function (for example, constructing an email client directly in business logic).

Information hiding

David Parnas’s 1972 paper “On the Criteria to Be Used in Decomposing Systems into Modules” argued that you should split a system around design decisions likely to change, and have each module hide one such decision. If the storage format may change, only the storage module should know the format. This is a better rule than “one module per step of the process”, which is how many beginners split code.

Clear interfaces

The interface is what other code is allowed to depend on: function signatures, public methods, and documented behaviour. Keep it small. Whatever you expose becomes something you must keep working. In Python the convention is a leading underscore for internal names; in Java and C++ use private; in JavaScript modules export only what callers need.

Separation of concerns

Keep different kinds of work apart: getting data, deciding what to do with it, and presenting or sending the result. When one function does all three, it is hard to test and hard to reuse.

A worked example: from one function to modules

Here is a function that totals paid orders and sends a report. It works, but the calculation, the formatting and the delivery are fused, and the only way to check it is to actually send something:

def send_report_v1(orders):
    total = 0
    for o in orders:
        if o["status"] == "paid":
            total += o["amount"]
    text = f"Paid total: ${total / 100:.2f}"
    print("EMAIL:", text)       # delivery is hard-wired here

Separate the three jobs and pass in the one thing that varies, the way the report is delivered:

def paid_total(orders):
    return sum(o["amount"] for o in orders if o["status"] == "paid")

def format_report(total_cents):
    return f"Paid total: ${total_cents / 100:.2f}"

def send_report(orders, send):
    send(format_report(paid_total(orders)))

orders = [
    {"status": "paid", "amount": 1250},
    {"status": "open", "amount": 900},
    {"status": "paid", "amount": 300},
]

send_report(orders, lambda text: print("EMAIL:", text))
# EMAIL: Paid total: $15.50

Each function now has one reason to change. The tax rule lives in paid_total, the wording in format_report, the channel in whatever you pass as send. And testing needs no email server:

sent = []
send_report(orders, sent.append)
assert sent == ["Paid total: $15.50"]
assert paid_total([]) == 0
print("tests pass")   # tests pass

Passing the dependency in as an argument is dependency injection in its simplest form. In object-oriented code you do the same through a constructor, and you describe what the dependency must do with an interface (in Python, a Protocol or an abstract base class):

from typing import Protocol

class Sender(Protocol):
    def send(self, text: str) -> None: ...

class ConsoleSender:
    def send(self, text): print("CONSOLE:", text)

class FakeSender:
    def __init__(self): self.messages = []
    def send(self, text): self.messages.append(text)

class ReportService:
    def __init__(self, sender: Sender):
        self.sender = sender
    def run(self, orders):
        self.sender.send(format_report(paid_total(orders)))

ReportService(ConsoleSender()).run(orders)   # CONSOLE: Paid total: $15.50
fake = FakeSender()
ReportService(fake).run(orders)
print(fake.messages)                         # ['Paid total: $15.50']

Swapping the console for a real email or Slack sender means writing one new class, with no change to ReportService. We cover the idea further in understanding dependency injection.

Modularity at different levels

Level Unit Typical tools
Code Functions and classes Small functions, classes with a narrow responsibility
Project Files, modules, packages Python modules and packages, ES modules, Java packages
Application Layers or domains Separate “billing”, “users”, “search” areas with clear boundaries
System Services Separately deployed services with APIs between them

The rules are the same at every level: hide details, keep interfaces small, avoid circular dependencies. The cost is different. A function boundary is free. A service boundary adds network calls, versioned APIs, deployment pipelines and failures that were not possible in one process.

Modularity across paradigms

  • Procedural: functions plus a header file (C) or module (Python) with a public surface. Group related functions and keep the data they share private to the file.
  • Object-oriented: classes bundle data with the operations on it. Interfaces let you substitute implementations. Be careful with deep inheritance, which couples a subclass tightly to its parent; prefer composition (a class holds a collaborator) in most cases.
  • Functional: pure functions that take input and return output, with no hidden state, compose easily and are easy to test. paid_total above is one.

Common mistakes

  • Over-modularizing. Twenty tiny classes, each with one method, that must all be read to understand one feature. Indirection has a cost: every layer is something a reader has to follow. Split when a piece has a reason to change independently or to be reused, not because a principle says small is good.
  • Splitting by step instead of by decision. “Step 1 module, step 2 module” tends to leak shared assumptions between them. Parnas’s advice, to split around things likely to change, avoids this.
  • Circular dependencies. If A imports B and B imports A, they are really one module wearing two names. Move the shared piece to a third module, or invert one dependency through an interface.
  • Leaky interfaces. Returning an internal list that callers then modify, or exposing database rows to the UI, welds the modules back together. Return copies or purpose-built values.
  • Jumping to microservices. Microservices apply modularity at system level, but they also bring network failures, distributed debugging and operational work. Many teams get most of the benefit from a well-structured single application with clear internal module boundaries, and split out services only when scale or team independence requires it.
  • Abstracting too early. An interface with only one implementation, written “in case”, is often wasted. Add it when the second implementation, or the test fake, appears.

How to make existing code more modular

  1. Write or find a test first, even a crude one that records current output, so you notice breakage.
  2. Find a function that does more than one thing and extract the pieces, as in the report example. Name each by what it does.
  3. Look for hard-coded collaborators (database connections, clock, HTTP calls) and pass them in.
  4. Look for shared mutable state and move it behind one module’s functions.
  5. Check imports. If a “low-level” module imports a “high-level” one, the dependency points the wrong way.
  6. Repeat in small steps, running tests after each. Our post on when and how to refactor goes into the process.

Why it matters for interviews

In coding rounds, short helper functions with clear names make your solution easier to explain and to debug under time pressure. In design rounds, interviewers want to see you split a system into components with defined responsibilities and talk about the interfaces and trade-offs between them. Practice the first part by writing small functions from the start; the Why Functions lesson is a short refresher, and the AlgoCademy exercises are a place to practice. For readability tips that go with this, see code readability and maintainability.

A lesson in AlgoCademy: the step to write, the line typed in the editor and checked, Step 3 passed; then a typo, the error pointing at its line, the fix, and Step 4 passed.

Before you go

Start thinking like a software engineer.

Learn to code and solve interview problems, one small, checked step at a time.

Try Why Functions free

No account needed. You write real code in your browser.