Achieving modularity
medium 45 minA module is a part of the program with a job, a small public face and a hidden inside.
Video lesson · Chapter 1 of 6
Make a prediction
Achieving modularity
1:01Reel
Theory
Read or listen first. About 2 min.
What it is
A module is a group of code with one responsibility, a public interface and a hidden implementation. In Java it may be a package or a module, in Python a package, in TypeScript a folder with an index.ts, in C++ a header with a source file or a C++20 module.
Two measures describe it. Cohesion: how much the things inside belong together. Coupling: how much the module must know about others, the topic of Reducing coupling. We want high cohesion and low coupling.
The most useful question is not *what does this code do* but what does it hide? A module earns its border by hiding a decision that may change: how tokens are stored, how prices are computed, which bank we use.
Why it exists
People can hold only so much in their head. With modules you read one inside and a few faces, not the whole program.
Teams can work next to each other: a change inside a module needs no meeting. Tests can run one module with small fakes for the others.
It keeps a choice open. A module with a clean border can later become a library or a service. A tangle cannot. But a module alone is not deployed alone: inside one program all modules are released together.
A short history
1972
David Parnas compares two ways to cut the same program. Cutting by processing steps makes a change touch many modules. Cutting by hidden decisions keeps it in one.
1974
Stevens, Myers and Constantine publish Structured Design, with cohesion and coupling as measures.
2014
Go 1.4 introduces internal packages: code under a directory named
internalmay be imported only from the tree around it. Go 1.5 enforces it for every repository.2017
Java 9 ships the module system (JEP 261, JSR 376). A module says which packages it exports and which modules it requires.
2020
Shopify describes the state of its Rails program as a modular monolith and publishes Packwerk, a tool that checks boundaries.
Words to know
- Module
- A part with a job, a public face and a hidden inside.
- Public interface
- The names others may use. Also called API or face.
- Cohesion
- How strongly the parts inside belong together.
- Coupling
- How much a module must know about others.
- Package by feature
- Folders by topic: auth, orders, products.
- Package by layer
- Folders by kind of class: controllers, services, repositories.
- Modular monolith
- One program, one release, with enforced borders inside.
- Acyclic dependencies
- Following the arrows never leads back to the start.
- Stable abstraction
- An interface that many use and that rarely changes.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
List the decisions that may change. Storage, rules, vendors, formats
Understand it
A train from one block
Asha and Max build a toy train, twice.
The wagon is not the point. The hook is.
From one lump to modules
Everything in one class
1/3Six jobs
Login, search, checkout, refund, reports, messages. They share fields, so they can change each other.
depends onuses
Four modules, each shown by its face
1/3One feature asks
Orders needs three answers: who is this, what does it cost, and please tell them.
usesimplements
Depend on
- public names
- interfaces and small value types
- events with a version
- ids of things others own
Do not depend on
- internal classes
- another module's tables
- the order of its private steps
- its exceptions from a vendor
Cohesion: what belongs together
From weak to strong
| Kind | Held together by | Example |
|---|---|---|
| Coincidental | nothing | utils: send email, format date, validate password, parse JSON |
| Logical | the same kind of thing | all validators of all features |
| Temporal | the same moment | everything done at start |
| Procedural | one order of steps | check rights, then open file |
| Communicational | the same data | all reports on the sales table |
| Sequential | output feeds the next | read, parse, validate |
| Functional | one job | auth: login, logout, check token, reset password |
A folder named utils, common or helpers is the usual sign of the first row. Move each function to the module that uses it. What is left and is used by many (a date format, a retry) becomes a small module with a real name.
Package by feature or by layer
by feature by layersrc/ src/ auth/ controllers/ AuthController AuthController AuthService OrderController UserRepository ProductController AuthTypes services/ orders/ AuthService OrderController OrderService OrderService ProductService OrderRepository repositories/ products/ UserRepository ProductController OrderRepository ProductService| By feature | By layer | |
|---|---|---|
| A change to one feature | one folder | three or more folders |
| Hide the repository | yes: private to the folder | no: it must be public for the services folder |
| Delete a feature | delete a folder | search |
| See all controllers at once | search | one folder |
| Fits | programs with several features | very small programs, or inside one feature |
Five principles
One responsibility
Auth handles who you are. It does not send invoices. See Single responsibility.
Information hiding
Export
Auth, hide the token store. If you can change it without telling anyone, it is hidden.Explicit dependencies
Needs stand in the constructor and in the module file. No hidden globals.
Stable abstractions
Depend on
PaymentGateway, not on the client of one bank.No cycles
Orders uses products uses inventory, and never back. See Circular dependencies.
One request across three modules
How each language draws the border
| Language | Public face | Hides with | Who enforces it |
|---|---|---|---|
| Java | exports com.app.auth.api in module-info.java | packages not exported, package private classes | compiler and JVM |
| Python | __init__.py with imports and __all__ | leading underscore, internal folders | nobody. __all__ only steers import *. A linter must check |
| TypeScript | index.ts, or exports in package.json | names not exported | inside one project nothing stops a deep import: lint rule. For packages: Node.js refuses paths that are not in exports |
| C++ | header, or export module auth; | source file, pImpl, names not exported | compiler and linker |
| Go | names with a capital letter | lower case names, internal folders | compiler |
// modules/auth/index.ts: the public contract of the moduleexport type { Auth, AuthResult, LoginCredentials } from "./auth.types";export { buildAuth } from "./build";// not exported, so nobody should know them:// AuthService, Tokens, PasswordHasher, UserRepository, AuthConfigWhere does this code go?
Find the home
Orders needs the customer's shipping address, which lives in the customers module.
BreaksRead the customers table
- How
- One join, no new method.
- Limit
- The schema of customers is now public. Rules such as hidden addresses are skipped.
- Choose when
- Never across modules.
WorksImport CustomerRepository
- How
- Typed, and the query exists.
- Limit
- Orders now sees everything the repository can do, also delete. It is the inside.
- Choose when
- As a step in a migration.
Strongcustomers.address_for(customer_id)
- How
- One method on the face that returns a small value. Orders stores a copy with the order.
- Limit
- A method per need. If it grows, the border may be in the wrong place.
- Choose when
- The normal case. The copy is right too: an order keeps the address it was sent to.
What you gain, and what it costs
| Benefit | How it shows | Condition |
|---|---|---|
| Maintainability | a change stays in one folder | the border follows what changes together |
| Testability | a module runs with fakes of its neighbours | dependencies are passed in |
| Reuse | auth serves a second program | no import of the first program |
| Teams | one team owns one module | faces change rarely and with notice |
| Understanding | read a face and not an inside | small faces, good names |
| Later split | a module can become a service | own data, no cycles. Until then it is released with the rest |
The costs: faces must be designed and kept, a simple call becomes two, types are translated at the border. A wrong border is worse than none, because each feature then crosses it. In a new program start with few, large modules and split when the history shows where.
Is this border good?
Summary
The whole topic in one minute.
Modularity means parts with one job, a small public face and a hidden inside. Good borders hide decisions that may change, so a change stays in one module. Package by feature, keep dependencies acyclic, and pass only small values across.
Languages help to different degrees, so let the build check imports, internals and cycles. Give each module its own data. A modular monolith is a fine place to stay; split into services when independent release, scale or failure is worth the network.
- A module has a job, a small face and a hidden inside.
- Cut by decisions that may change, not by steps or by kinds of class.
- High cohesion inside, low coupling between, arrows in one direction.
- Features outside, layers inside.
- Own your data: no other module reads your tables.
- A border that the build does not check will fade.
Sources
- JEP 261: Module System
- Go 1.4 release notes: internal packages
- Node.js: package entry points and exports
- Python tutorial: modules and packages
- Spring Modulith: Fundamentals
- Shopify: The State of Shopify's Monolith (2020)
- Packwerk
- Martin Fowler: MonolithFirst
- Parnas: On the Criteria To Be Used in Decomposing Systems into Modules