Logbook

Chaos is death, order is life

Software dies of entropy, one feature at a time.It lives by order, one pruning at a time.

Updated

I have been working long enough into software to know that without a structure growing software end-up in as a big ball of mud where the entropy is high and the system becomes hard to understand.

The entropy in system is created one new feature at a time, it is the death by a thousand cut

As an evolving program is continually changed, its complexity, reflecting deteriorating structure, increases unless work is done to maintain or reduce it.

Meir M. Lehman, Programs, Life Cycles, and Laws of Software Evolution, 1980

The solution against it is energy and structure which create order

The energy is the constant effort a software engineer do to maintain the system he growth

The structure is the mental model he uses to handle the entropy of the software

This article describe the concepts around the structure i believe helps software system to handle the entropy

Layered architecture

Source code dependencies can only point inwards.

Robert C. Martin, The Clean Architecture, 2012

Let's imagine you are at the new house friend, everything is fine, you are enjoying a good drink. She is going to prepare the table for everyone and ask you to put some trash into the bin. You go open the cupboard under the sink - nothing, there are plates here and some tea towels. She then say really casually "oh the bin is in the garage". You should be confused and rightly if you ask me. The garage responsability is not to handle the bin which you will use really regularly while you are cooking. The expected place is in the kitchen.

In software system the place where you put code should be layer, a layer as responsibilities it's a mental model that help you structure your code by having one point of entry where you handle one concept

The different layers are :

LayerPartSide
DomainCore-
PortsCore-
Use-casesCore-
StorageAdapterDriven
ConnectorAdapterDriven
SystemAdapterDriven
ControllerAdapterDriving
PresenterAdapterDriving

We divide them in two category :

Important : One key aspect of this architecture is to isolate the business logic so we don't have to change it later in case of a switch or technology. We don't want to pollute the business logic with implementation details, tech choices, etc..

Core:Domain

Core:Use-cases

Core:Ports

Adapters:Storage(driven)

Adapters:Connector(driven)

Adapters:System(driven)

Adapters:Controler(driving)

Adapters:Presenter(driving)

The layers and their dependencies

Diagram of the layers: the core holds Domain, Contracts and Use-cases behind Ports; the driven adapters (Repository, Connector, System) implement the ports; the driving adapters (Controller, Presenter) call the use cases and the contracts

Every arrow points towards the core.

Composition Root

Once we have theses layers in place the application need to compose them (adapter, port, etc..), in order to that we use a container file that is responsible for knowing which adapter goes to which port

It lives in the app because it is the only place that knows which database, which vendor, which clock. It imports every adapter and every entity's controller, and nothing imports it.

One package, two apps

Diagram of a package holding one entity with its core and adapters, and the apps (web-app, server) each holding a composition root that points to the package

The apps depend on the package, never the reverse.

Domain Modeling

Schema First

The domain is modelled as schemas, not as types. A schema is a runtime value, so one declaration gives four things that would otherwise be written by hand and drift apart: the static type, inferred from it; the validator, run at every boundary where data enters;

Schema:Entity

A shape with an identity. It stays the same thing as its fields change, so it has an id, a storage, and the invariants that make it valid. Built only by the domain, it is the canonical form of the data and never leaves the core.

Schema:ValueObject

A shape with no identity. Equal to any other value with the same fields, never modified but only replaced, validated once at construction and valid everywhere after. Branded so that two values of the same primitive type cannot be confused.

Schema:Contract

A shape that leaves the core. Derived from an entity by pick, omit and extend, with no rules of its own, it is what controllers, presenters and views depend on instead of the entity, so that the entity can change without breaking them. Lives in contracts, next to the function that builds it from the entity

Errors

There are three kinds of error :

Error:Domain

An invariant or a rule was not satisfied. They are defined in Core:Domain, next to the rule that issues them, because the refusal is part of the rule.

Error:NotFound

Something expected is absent. It returns the absence as a value and the use case decides whether that absence is an error. So NotFound is defined in the application layer, produced only by use cases, and shown to the user like a domain error.

Error:System

The system failed for reasons unrelated to the business: network down, database unreachable, a provider throttling us, a configuration value missing. These are born in an adapter, at the first line that can throw, and wrapped into a value with the original cause attached. Only the operator can fix them, so they are logged with their cause, retried when transient, and shown to the user as a plain failure with nothing from the inside.

Two concepts carry all three.

Errors as values

An error is data with a tag, returned rather than thrown. The only place an exception is allowed is the controller, when the protocol demands one.

Result monad

Every function that can fail returns Result<T, E>. The signature lists what can go wrong, the caller cannot ignore it, and a switch on the tag with no default stops compiling the day a new error is added. Ports declare the error union of each method, so a use case sees a closed set and chooses what to do with each case: retry, switch source, skip, or pass it up.

Each error is translated exactly once, at a boundary. The adapter turns an exception into a value. The controller turns the value into the protocol's vocabulary: an HTTP status, an MCP isError, an exit code. Nothing in between touches it, which is why a tag created in a repository arrives at the controller unchanged.

Because errors are typed data rather than stack traces, an external system calling ours receives a precise error it can act on.

Vertical Slicing

Minimize coupling between slices, and maximize coupling in a slice.

Jimmy Bogard, Vertical Slice Architecture, 2018

Code is grouped by capability first and by layer second. A slice is one thing the user does and the aggregate it touches, and it is one folder that holds every layer it needs:

entity/
  domain/
  application/
  contracts/
  storage/
  connectors/

Typesafe

Well-type programs cannot “go wrong”.

Robin Milner, A Theory of Type Polymorphism in Programming, 1978

The goal is to learn about a mistake at compile time rather than in run time. How much a language lets you do that depends on whether its type system is sound.

A sound type system guarantees that a value of type T is really a T at runtime. Rust is sound outside unsafe: the program may still panic, but it will never hold a string where it believes there is an integer.

An unsound type system accepts programs where a value can carry a type it does not have. TypeScript is unsound by design: any, as, JSON.parse

Tooling

Monorepo

The whole system lives in one repository. A change to runs touches its domain, its storage, its contracts and the app that exposes it in a single commit: no package versions to bump between them, no release order to get right. You can also check architecture rules as everything is in the repo.

package/
  entity/
    domain/
    application/
    contracts/
    storage/
    connectors/
    controllers/
    presenters/
  config/
    tsconfig.json
    eslint.json
apps/
  web-app/
    container.ts
  server/
    container.ts
  server-mcp/
    container.ts

Each entity folder is one slice and one workspace package, complete from domain to controller. An app is a composition root and nothing else: it builds the adapters, then hands a server and a deps bag to each entity's controller.

Linting

Linting. A linter reads the code and refuses patterns we have agreed are mistakes. It catches the small things that are tedious to review by hand. A linter runs in seconds, on save and in CI.

Each coupling row of the cards becomes one import rule: the domain may not import a database library, the application may not import an adapter, a controller may only import its own slice. A no-cycle rule keeps slices out of each other.

Formatting

One formatter, no options, run on save and in CI

DevTools

Dev tools make life easier and application more understandable i like to use :

Testing

Program testing can be used to show the presence of bugs, but never to show their absence!

Edsger W. Dijkstra, Notes on Structured Programming, 1970

The three levels of tests

Testing pyramid: unit tests at the base check the logic and functions inside a module, integration tests in the middle check how a package integrates, end-to-end tests at the top check how the whole system reacts

Wider means more tests. Higher means slower and more costly.

Unit

I like to unit test function to test edge cases and make sure they are Total functions

It's also a good documentation when you discover a case that could go wrong you can create an associated unit test to bit.

Knowing every possible edge cases in advance could be hard but it's simple to test from a pure function perspective

Integration

Integration test are from the perspective of a package/slice. They are here to ensure a part of the system behave has expected. The classical case is calling the controller knowing the inputs and expecting outputs. The test shouldn't know about how the module/package works and internals or dependencies and which layer get traversed

End-to-end (E2E)

The end-to-end test are from the user interface point of view

They are slow and can break often. But they provide a good check if the system is working correctly

I used them to check happy path only - or really important edge case that that happened in production and i want a Tripwire on

What each kind of test covers

Diagram of the test scopes: an end-to-end test wraps the whole system, an integration test wraps each package, and unit tests sit inside each package

Unit: one function. Integration: one package. End-to-end: the whole system.

Documentation

ADR

This document describes the structure; a project's ADRs record where and why it deviated. Keep them in docs/adr/, numbered, one decision per file, each with a status, a date, the decision in a few lines, and the evidence that led to it. The first three are always the same: the architecture and its enforcement, the storage choice, and the error and validation stack. Record the spike that justified each, with its date, so a later reader can tell a tested choice from a habit. An ADR is amended, never rewritten: when a decision changes, a new ADR supersedes the old one and both say so.

Infrastructure

One page and one diagram: which processes exist, where each runs, what it talks to, what configuration and secrets it needs, and how it gets deployed. It is the only place the real constraints behind the code are visible, and the first thing an on-call reader opens. It changes rarely, so it is written by hand and reviewed with every deployment change.

Database (EntityRelationship Diagram)

An entity relationship diagram generated from the schema definitions, on every build. Never drawn by hand: a drawn diagram is a snapshot, and the schema moves.

APIs

A reference of every endpoint, its inputs, outputs and errors, with examples. Schema first makes this free: the contracts produce an OpenAPI document and a renderer such as Scalar serves it. Nobody maintains it, so it is never out of date.

Further reading

The books and articles behind this article, in the order they appear.

Big Ball of Mud

Brian Foote and Joseph Yoder, 1997

Where the name comes from: how systems lose their shape, and why.

Domain-Driven Design

Eric Evans, 2003

Entities, value objects, aggregates and invariants.

Parse, don't validate

Alexis King, 2019

Check data once, at the boundary, and keep the proof in the type.

Vertical Slice Architecture

Jimmy Bogard, 2018

Grouping code by what the user does, not by layer.

Test Pyramid

Martin Fowler, 2012

Many unit tests, fewer integration tests, few end-to-end tests.