AlgoViz

Achieving modularity

medium 45 min

A 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

0:00 / 4:58

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

  1. 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.

  2. 1974

    Stevens, Myers and Constantine publish Structured Design, with cohesion and coupling as measures.

  3. 2014

    Go 1.4 introduces internal packages: code under a directory named internal may be imported only from the tree around it. Go 1.5 enforces it for every repository.

  4. 2017

    Java 9 ships the module system (JEP 261, JSR 376). A module says which packages it exports and which modules it requires.

  5. 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.

Step 1 of 5

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.

Wagons that hook on

The wagon is not the point. The hook is.

From one lump to modules

Everything in one class

ShopApp- users- products- orders- db: Connection+ login(name, pw)+ search(text)+ checkout(cart)+ refund(id)+ salesReport()+ sendSms(to, text)

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

«interface»Orders+ create(token, items)

1/3One feature asks

Orders needs three answers: who is this, what does it cost, and please tell them.

usesimplements

Each arrow ends at a face. Nothing points back to Orders.

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

KindHeld together byExample
Coincidentalnothingutils: send email, format date, validate password, parse JSON
Logicalthe same kind of thingall validators of all features
Temporalthe same momenteverything done at start
Proceduralone order of stepscheck rights, then open file
Communicationalthe same dataall reports on the sales table
Sequentialoutput feeds the nextread, parse, validate
Functionalone jobauth: login, logout, check token, reset password
The names come from structured design. In a review two questions are enough: what is its one job, and does it change for one reason?

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

Text
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
The same classes. Add a field to orders and count the folders you open.
By featureBy layer
A change to one featureone folderthree or more folders
Hide the repositoryyes: private to the folderno: it must be public for the services folder
Delete a featuredelete a foldersearch
See all controllers at oncesearchone folder
Fitsprograms with several featuresvery small programs, or inside one feature
Layers are not wrong. Use features outside and layers inside a 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

Orders gets an id, not a user object with a password hash. A face gives only what is needed.

How each language draws the border

LanguagePublic faceHides withWho enforces it
Javaexports com.app.auth.api in module-info.javapackages not exported, package private classescompiler and JVM
Python__init__.py with imports and __all__leading underscore, internal foldersnobody. __all__ only steers import *. A linter must check
TypeScriptindex.ts, or exports in package.jsonnames not exportedinside 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 exportedcompiler and linker
Gonames with a capital letterlower case names, internal folderscompiler
TypeScript
// 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, AuthConfig
Export the interface and a way to get one. If you export the class, its constructor and all its helpers become part of the promise.

Where 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

BenefitHow it showsCondition
Maintainabilitya change stays in one folderthe border follows what changes together
Testabilitya module runs with fakes of its neighboursdependencies are passed in
Reuseauth serves a second programno import of the first program
Teamsone team owns one modulefaces change rarely and with notice
Understandingread a face and not an insidesmall faces, good names
Later splita module can become a serviceown 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