Skip to content

Coupling and Dependencies ​

Cohesion, from Chapter 11, judges a design one class at a time: it asks whether everything inside a class belongs together, and guides designers towards one invariant per class. Cohesion is necessary for a good design, but it is not sufficient. A system can be built entirely from cohesive classes and still be difficult to change, because the difficulty lies in the connections between the classes. Tightly-connected classes, or classes with many connection points, are hard to change.

You might think that if software is sufficiently well-designed, the code will not need to change later. But code changes throughout its life. Requirements arrive after release, libraries publish new major versions, the services a program calls change their responses, platforms deprecate the interfaces a system was built against, and the rules governing the data are rewritten. None of these changes are failures of the original design, because the pressure to change comes from outside the program. Design cannot prevent these changes, but it can make them easier to carry out.

Coupling describes how tightly one class is bound to another. The principle that follows from it is that a class should depend on as little as possible, as loosely as possible. To judge a decomposition, we need to consider both cohesion and coupling.

The Ripple Effect ​

Let's go back to the music app from Chapter 11. Playlist still owns the navigation invariant, and PlayHistory still owns the history invariant. Both classes are as cohesive as when they were designed.

But the rest of the system has changed around them:

As a listener, I want to see a summary of what I played this week, so that I can rediscover songs I enjoyed recently.

Let's say we write a new WeeklyRecap class to implement this. The history is already recorded, so the quickest implementation asks Playlist for the history and summarises it:

typescript
class WeeklyRecap {
    /** The playlist whose history is summarised. */
    private readonly playlist: Playlist;

    /**
     * Creates a recap of the given playlist's history.
     *
     * @param {Playlist} playlist the playlist whose history is summarised.
     */
    public constructor(playlist: Playlist) {
        this.playlist = playlist;
    }

    /**
     * Describes this week's listening.
     *
     * @returns {string} a one-line summary of the recent play history.
     */
    public summary(): string {
        const recent: Song[] = this.playlist.recentlyPlayedSongs();
        let text: string = "You played " + recent.length + " songs";
        if (recent.length > 0) {
            text = text + ", starting with " + recent[0].title;
        }
        return text;
    }
}

Nothing here is obviously wrong. WeeklyRecap is cohesive: it has one job and provides only that feature. It does not touch the navigation invariant or the history invariant. The code compiles and works, and it would probably pass a code review.

But let's consider what WeeklyRecap has assumed about Playlist and PlayHistory:

  • It assumes that the history comes back as an array.
  • It assumes that the array is ordered with the most recent play first.
  • It assumes that its elements are Song objects.
  • It assumes that each Song has a title.

Most of these facts are written in the contract of PlayHistory.songs(). But that contract leaks PlayHistory's representation! So now, WeeklyRecap depends on implementation details of PlayHistory, rather than the abstract value of PlayHistory.

Let's see what happens when something changes. The user story asks for what was played this week. The current design cannot answer that question, because there's only a list of recent songs, with no information of when they were played.

What might we do now? Perhaps PlayHistory needs to store the time of each play, not just the Song? We can get it to store PlayRecords instead:

typescript
type PlayRecord = {
    song: Song;
    /** When the song was played, in milliseconds since the epoch. */
    playedAt: number;
};

Changing the internal representation from Song[] to PlayRecord[] is a small change, made in the class that owns the history invariant. A cohesive decomposition is supposed to make this kind of change safe. But the change will break many things:

  • PlayHistory.songs(), whose return type no longer matches what the class stores.
  • Playlist.recentlyPlayedSongs(), which forwards that return value.
  • WeeklyRecap.summary(), which indexes the result and reads .title from it.
  • Every test that built up a history and asserted on the array that came back.
  • Any other screen, exporter, or report that asks for the history in the same way.

One change to one cohesive class has forced edits in code that has no interest in how the history is stored. We could hide the change by making PlayHistory return the songs behind the PlayRecords... but then callers could not see when each song was played, which was the reason for the change.

All these things that break are the ripple effect: a change that should have been local propagates outward along the dependencies. The cost of the change depends on the number of places that have to be revisited, rather than on the size of the change itself. An engineer might estimate "add timestamps to the history" as an afternoon's work, and then find that most of the afternoon goes to fixing other classes.

The ripple effect has three costs.

  1. The edits themselves are the most visible cost once the work begins, but also the smallest.
  2. The second cost is regression risk. Each of those edits modifies code that already worked and was already tested, and every modification is an opportunity to break behaviour that had nothing to do with the original request. The Open/Closed Principle makes a related argument in Chapter 16: a change that cannot be contained puts working code at risk.
  3. The third cost is coordination. In a large system, the classes that must be revisited are not all yours. They may be owned by other developers, reviewed by other people, covered by other people's tests, and scheduled against other deadlines. A change that reaches across those boundaries requires coordinating with other people as well as editing code.

What Coupling Is ​

Two classes are tightly coupled when a change to one is likely to force a change to the other. They are loosely coupled when each can change without requiring changes to the other.

A practical way to assess coupling is to ask: how much must you know about B to write or change A? In principle, WeeklyRecap only needs one thing: the list of songs played since a given time. But WeeklyRecap above had to know the shape of the array PlayHistory stores, so the two classes are tightly coupled (even though WeeklyRecap never mentions PlayHistory by name!).

Coupling complements cohesion, and the two are best considered together:

  • Cohesion is judged within a boundary: do the parts of this class belong together?
  • Coupling is judged between boundaries: how much does this class depend on that one?

Both serve the same goal: keeping changes local. High cohesion keeps a change local by placing everything one invariant needs in one class, so there is a single place to edit. Low coupling keeps a change local by limiting how far the effects of that edit can spread.

Coupling is easier to reason about when the dependencies are drawn as a diagram.A dependency exists from A to B when A needs B to compile or run. For example, A might construct a B, hold one as a field, take one as a parameter, call one of its methods, or read its data.

Draw all your classes, and draw a line between A and B when A has a dependency to B. Now you have a dependency graph! The classes are nodes and the dependencies are arrows. Each arrow points from the dependent class to the class it relies on.

plantuml Diagram
Dependencies in the music app. Every arrow is a path a change can travel along.

Following an arrow backwards tells you what a change to a class can break. Playlist depends on PlayHistory directly, and three more classes depend on Playlist. A change to PlayHistory can therefore affect all four of those classes, as well as any classes that depend on them.

Fan-In and Fan-Out

Two numbers summarise a class's position in the dependency graph. Fan-out is the number of classes a class depends on. It indicates how fragile the class is, because a change to any of those classes can break it. Fan-in is the number of classes that depend on a given class. It indicates how expensive the class is to change, because each of those classes may need to be revisited when it changes.

The two numbers call for different design choices. A class with high fan-in should be kept small and stable. Interfaces work well as high fan-in types because they have no implementation to change. A class with high fan-out usually connects many other objects together. A system should have few of these classes, and they should sit in its outer layer, close to where the program starts.

import Is a Dependency

In TypeScript, a file's dependencies are listed at the top of the file. Each import names something the file cannot compile without, so the import list summarises what the file is coupled to. A file with twenty lines of imports has a large fan-out, and you can see this before reading any of its code. Not all imports carry the same weight. Importing a type or an interface commits you only to a shape. Importing a class that you construct with new commits you to that specific implementation.

Degrees of Coupling ​

Coupling is a matter of degree, and some kinds of coupling have specific names. Understanding each kind, its impact and how it arises is more useful than memorising the names. The table below lists the forms from tightest (worst) to loosest (best). The goal is to move each dependency as far down the list as the design allows (ideally, data coupling, where the two classes exchange only the values the operation need).

FormWhat it looks likeIn the music app
ContentOne class reads or writes another's internal state directly.playlist.playHistory.recent.push(song)
CommonTwo classes share mutable state that belongs to neither.Both read a module-level currentListener.
ControlA caller passes a flag that decides which branch the callee takes.summary(true) meaning "weekly rather than daily".
StampA caller passes a whole object when only part of it is needed.new WeeklyRecap(playlist) when only the history is used.
DataA caller passes exactly the values the callee needs.songsSince(startOfWeek)

The original WeeklyRecap is stamp coupled: it is given an entire Playlist when it only needs the history. It is also close to content coupling, because the array it receives exposes how PlayHistory stores its data internally.

Control coupling is easy to miss because it looks harmless. When a parameter selects which behaviour a method performs, the caller is steering the callee's internal logic. The caller must understand the callee's branches, and adding a third mode requires changing both the caller and the callee. A method that takes a flag is usually two methods that have not yet been separated.

Control Coupling and the Boolean Parameter

The examples in this tooltip use PlayLog, the one-method interface defined in the next section, Loosening WeeklyRecap. Its method songsSince(time) returns the songs played at or after a given time.

Suppose the recap should cover either the past day or the past week. The smallest change that supports both is a boolean flag:

typescript
class Recap {
    /** The history the recap summarises. */
    private readonly log: PlayLog;

    /**
     * Creates a recap of the given history.
     *
     * @param {PlayLog} log the history to summarise.
     */
    public constructor(log: PlayLog) {
        this.log = log;
    }

    /**
     * Describes recent listening.
     *
     * @param {number} now milliseconds since the epoch.
     * @param {boolean} weekly true for the past week, false for the past day.
     * @returns {string} a one-line summary of the period.
     */
    public summary(now: number, weekly: boolean): string {
        const dayInMs: number = 24 * 60 * 60 * 1000;
        let since: number = now - dayInMs;
        if (weekly) {
            since = now - (7 * dayInMs);
        }
        const songs: Song[] = this.log.songsSince(since);
        return "You played " + songs.length + " songs.";
    }
}

At the call site, that reads:

typescript
recap.summary(now, true);

This design has two shortcomings. The first is readability. The argument true says nothing about what was requested, so a reader has to open summary(..) to find out.

The second shortcoming appears when a monthly recap is requested. A boolean cannot represent three modes, so the signature has to change, and every existing call has to change with it. The usual next step is to add a second flag, which makes things worse. A signature that allows summary(now, false, true) also allows summary(now, true, true), a combination with no meaning that the type checker will still accept.

When there are only a few fixed modes, the fix is to give each mode its own named method instead of passing the choice as an argument:

typescript
class Recap {
    /** The history the recap summarises. */
    private readonly log: PlayLog;

    /**
     * Creates a recap of the given history.
     *
     * @param {PlayLog} log the history to summarise.
     */
    public constructor(log: PlayLog) {
        this.log = log;
    }

    /**
     * Describes the listening in the day before the given time.
     *
     * @param {number} now milliseconds since the epoch.
     * @returns {string} a one-line summary of the past day.
     */
    public dailySummary(now: number): string {
        const dayInMs: number = 24 * 60 * 60 * 1000;
        return this.summarySince(now - dayInMs);
    }

    /**
     * Describes the listening in the week before the given time.
     *
     * @param {number} now milliseconds since the epoch.
     * @returns {string} a one-line summary of the past week.
     */
    public weeklySummary(now: number): string {
        const weekInMs: number = 7 * 24 * 60 * 60 * 1000;
        return this.summarySince(now - weekInMs);
    }

    /**
     * Describes the listening at or after the given time.
     *
     * @param {number} since milliseconds since the epoch.
     * @returns {string} a one-line summary of the songs played since then.
     */
    private summarySince(since: number): string {
        const songs: Song[] = this.log.songsSince(since);
        return "You played " + songs.length + " songs.";
    }
}

A call to recap.weeklySummary(now) is clear on its own, and the shared work still lives in one place. Adding a monthly recap means adding a new method, and no working method has to be edited.

When the modes are not fixed, the flag stands in for a value. In this case, the method should take that value directly. summarySince can be made public, and the caller supplies whatever period it needs:

typescript
recap.summarySince(now - weekInMs);

This design supports every period, including ones nobody has asked for yet, without any branches. Replacing the flag with a value changes control coupling into data coupling. In general, watch for parameters whose meaning a reader cannot tell from the call site.

Loosening WeeklyRecap ​

To reduce the coupling in the original design, we should figure out exactly what WeeklyRecap needs---what questions it needs answered. Then, we should have PlayHistory provide only the information necessary to answer these questions.

The first step is to define the contract. WeeklyRecap needs to know what songs have played since last week. We can encode that need in an interface:

typescript
/**
 * A source of listening history, ordered most recent first.
 */
interface PlayLog {
    /**
     * Returns the songs played at or after the given time.
     *
     * @param {number} time milliseconds since the epoch.
     * @returns {Song[]} the matching songs, most recently played first.
     */
    songsSince(time: number): Song[];
}

PlayHistory implements the interface. The knowledge of how the history is stored, which leaked out when PlayHistory handed over its whole array, now stays inside the class.

Because PlayHistory answers a question instead of exposing a list, it is free to store its data however it likes:

typescript
class PlayHistory implements PlayLog {
    /** The latest play of each song, most recent first; each song appears at most once. */
    private readonly recent: PlayRecord[] = [];

    /**
     * Records that a song was played, moving it to the front.
     *
     * @param {Song} song the song that was played.
     * @param {number} playedAt milliseconds since the epoch.
     */
    public record(song: Song, playedAt: number): void {
        this.forget(song);
        this.recent.unshift({ song: song, playedAt: playedAt });
    }

    /**
     * Returns the songs played at or after the given time.
     *
     * @param {number} time milliseconds since the epoch.
     * @returns {Song[]} the matching songs, most recently played first.
     */
    public songsSince(time: number): Song[] {
        const found: Song[] = [];
        for (const record of this.recent) {
            if (record.playedAt >= time) {
                found.push(record.song);
            }
        }
        return found;
    }

    /**
     * Removes the record of the given song, if there is one.
     *
     * @param {Song} song the song to remove.
     */
    private forget(song: Song): void {
        const i: number = this.recent.findIndex((r: PlayRecord) => r.song === song);
        if (i !== -1) {
            this.recent.splice(i, 1);
        }
    }
}

WeeklyRecap now depends only on the PlayLog contract:

typescript
class WeeklyRecap {
    /** The history the recap summarises. */
    private readonly log: PlayLog;

    /**
     * Creates a recap of the given history.
     *
     * @param {PlayLog} log the history to summarise.
     */
    public constructor(log: PlayLog) {
        this.log = log;
    }

    /**
     * Describes the listening in the week before the given time.
     *
     * @param {number} now milliseconds since the epoch.
     * @returns {string} a one-line summary of the week's play history.
     */
    public summary(now: number): string {
        const weekInMs: number = 7 * 24 * 60 * 60 * 1000;
        const songs: Song[] = this.log.songsSince(now - weekInMs);
        if (songs.length === 0) {
            return "You played nothing this week.";
        }
        return "You played " + songs.length + " songs this week, starting with " + songs[0].title + ".";
    }
}
plantuml Diagram
WeeklyRecap depends on the PlayLog contract rather than on the class that keeps the data.

What if the Code Changes Again? ​

PlayHistory could now switch from an array to a map, limit itself to fifty entries, or save its data to disk, and WeeklyRecap would not change. The only remaining dependency is on one method signature. A single method signature is the smallest agreement the two classes need to work together.

The direction of the dependency has also changed. WeeklyRecap does not depend on PlayHistory, and PlayHistory does not depend on WeeklyRecap. Both depend on PlayLog, which has no implementation to change. Arranging dependencies so that they point at abstractions rather than concrete classes is the Dependency Inversion Principle from Chapter 16. Following it is a reliable way to keep coupling low.

Coupling in Tests ​

Coupling often shows up in the test suite first. A test that is hard to write usually indicates a design problem rather than a testing problem. To test the original WeeklyRecap, you needed a real Playlist, which needed a real PlayHistory, which needed songs recorded through the playlist in the right order. The test needed three classes to check one string.

The new WeeklyRecap needs none of that setup, because any object that implements PlayLog will work:

typescript
class StubLog implements PlayLog {
    /**
     * Returns the same two songs whatever the time.
     *
     * @param {number} time ignored.
     * @returns {Song[]} two fixed songs, most recent first.
     */
    public songsSince(time: number): Song[] {
        return [
            { title: "Bloom", artist: "Fernwood", durationSeconds: 214 },
            { title: "Ridgeline", artist: "The Cartographers", durationSeconds: 187 }
        ];
    }
}

test("the recap names the count and the most recent song", () => {
    const recap: WeeklyRecap = new WeeklyRecap(new StubLog());

    expect(recap.summary(0)).to.equal(
        "You played 2 songs this week, starting with Bloom."
    );
});

StubLog is a test double, like the ones in Chapter 14. In general, if a unit test requires you to construct a large part of the system, then the class under test is coupled to a large part of the system.

Diagnosing Coupling ​

Chapter 11 described ways to detect a badly split class, such as fields the invariant never mentions or methods that maintain a different invariant. Coupling also has signs that are visible in the code, and this section describes two of them. A third sign, a dependency that points in both directions, is covered in the next section.

Reaching Past a Neighbour ​

The Law of Demeter states: a method should only call methods on its own object, on its own fields, on its parameters, and on objects it creates.

Violations of this law result in a chain of calls that goes through one object to reach a second object, and then a third:

typescript
const city: string = order.customer().address().city();

Each step follows a relationship that the caller should not need to know about. This code depends on orders having customers, customers having addresses, and addresses having cities. A change to any of those three classes can break this line, even though the caller only wanted one string.

The fix is to ask the immediate neighbour for the value you want, rather than for the object that has it:

typescript
const city: string = order.shippingCity();

Order already knows how to find its shipping city, so it is the right class to provide it. The caller now depends on one class instead of three.

Not all chains of calls are problematic: the expression songs.filter(isRecent).map(toTitle).slice(0, 5) chains three calls, but it does not couple you to anything new. Every call returns an array, the same kind of value you started with, and no relationship between separate objects is followed.

To evaluate the Law of Demeter, rather than asking, "how many dots?", you should ask "how many classes must this line know about?" A chain over one type needs to know about one class, however long the chain is. order.customer().address().city() needs to know about three.


A related guideline is Tell, Don't Ask: tell an object what you need done and let it decide how to do it, rather than asking for its state and making the decision for it.

Here's some code that violates Tell, Don't Ask:

typescript
if (account.balance() >= amount) {
    account.setBalance(account.balance() - amount);
}

The caller has taken on a rule that belongs to Account: when a withdrawal is allowed, and what the balance becomes afterwards. Every caller that does this has its own copy of the rule, so changing the rule means finding and updating all of them. Account also cannot enforce its invariant, because callers can set the balance to anything they compute. If the caller tells the account what to do instead, the rule and the invariant stay in Account:

typescript
account.withdraw(amount);

Note the PlayLog design above follows the Tell, Don't Ask guideline. PlayHistory answers a question about the history itself, rather than passing internal state. A method whose body mostly calls other objects' getters usually belongs in a different class.

Interfaces and Extension ​

Strategic use of interfaces (or supertypes more generally) in client code can help us reduce coupling.

A dependency on a concrete class exposes the dependent class to everything that class does, and to every way it might change in the future. The original WeeklyRecap declared its field as a Playlist, so it was exposed to all of Playlist's public methods, even though it only needed a single query. Instead, we'd like WeeklyRecap to only depend on the query it needs. How do we do this? Go back to Chapter 14: write an interface, and depend only on this interface. We still need to keep the interface minimal to reduce coupling.

What about extension? Extension helped us reduce code duplication between related clasess. But consider a class SubClass that extends a class SuperClass. How tightly are SubClass and SuperClass coupled?

They are very tightly coupled, more than any type of coupling in the table at the start of the chapter. A subclass depends on its base class's implementation as well as its public contract: its protected members, and the order in which the base class calls its own methods. Chapter 15 described the result, the fragile base class problem: a change inside a base class can alter the behaviour of subclasses that were never edited.

So, make sure you use extension only for true is-a relationships. A subclass ends up depending on all the internals of a base class. If what you want instead is for a class to be able to use a few methods of another class, and especially if there is not clear is-a relationship between the classes, add a collaborator instead.

Dependency Cycles ​

When A depends on B and B depends on A, neither class can be read, tested, or changed without the other. The two classes effectively become a single unit. Chapter 11 made this point about ownership. Playlist holds a PlayHistory because it delegates recording to it, and giving PlayHistory a reference back to Playlist would have bound the two together in both directions.

Cycles are rarely designed deliberately. They usually appear when a class needs to notify the class that owns it. Suppose the music app should mark a song as a favourite once it has been played three times in a week. Counting plays is a job for the history, but the history currently keeps only the most recent play of each song. Suppose it is extended to keep every play, so that it can count them. The quickest implementation then has the history tell the playlist directly:

typescript
class PlayHistory {
    private readonly playlist: Playlist;   // a back-reference

    /**
     * Records that a song was played, and marks it as a favourite once it
     * has been played three times in a week.
     *
     * @param {Song} song the song that was played.
     * @param {number} playedAt milliseconds since the epoch.
     */
    public record(song: Song, playedAt: number): void {
        // ... record the play ...
        const weekInMs: number = 7 * 24 * 60 * 60 * 1000;
        if (this.playsSince(song, playedAt - weekInMs) >= 3) {
            this.playlist.markFavourite(song);
        }
    }
}
plantuml Diagram
A dependency cycle: each class now needs the other.

Playlist already depended on PlayHistory, so this creates a cycle. A reader tracing what happens when a song is played now has to move back and forth between the two files, and neither class can be tested without the other.

There are three ways to break a cycle, from simplest to most complex.

Cycle Fix 1: Reverse the Direction of the Question ​

The cheapest fix is usually to use the dependency that already exists, and let the class on that side ask the question. Playlist already depends on PlayHistory, so PlayHistory does not need to know about playlists at all. It only needs to answer questions about plays:

typescript
class PlayHistory {
    /**
     * Returns the songs played at least `times` times since `time`.
     *
     * @param {number} times the minimum number of plays.
     * @param {number} time milliseconds since the epoch.
     * @returns {Song[]} the qualifying songs, most recently played first.
     */
    public playedAtLeast(times: number, time: number): Song[] { /* ... */ }
}

class Playlist {
    /**
     * Returns the songs played at least three times in the week before the given time.
     *
     * @param {number} now milliseconds since the epoch.
     * @returns {Song[]} the favourite songs, most recently played first.
     */
    public favourites(now: number): Song[] {
        const weekInMs: number = 7 * 24 * 60 * 60 * 1000;
        return this.playHistory.playedAtLeast(3, now - weekInMs);
    }
}

This removes the cycle without introducing any new types, and the rule about what counts as a favourite now sits in Playlist with the playlist's other rules. The behaviour changes slightly: a song counts as a favourite only while it has three plays in the past week, instead of staying marked once it qualifies. Prefer this approach whenever the dependent class can pull the information it needs, rather than having its collaborator push it.

Cycle Fix 2: Invert One Direction with an Interface ​

Sometimes the collaborator has to start the interaction, because it is the only class that knows when the event occurred. In that case, the class sending the notification should define an interface for what it needs and depend on that interface. The other class then implements it:

typescript
interface PlayObserver {
    /**
     * Called when a song crosses the frequent-play threshold.
     *
     * @param {Song} song the song that crossed the threshold.
     */
    songBecameFrequent(song: Song): void;
}

class PlayHistory {
    private readonly observer: PlayObserver;   // not a Playlist
    // ...
}

class Playlist implements PlayObserver {
    /**
     * Marks a song that crossed the frequent-play threshold as a favourite.
     *
     * @param {Song} song the song that crossed the threshold.
     */
    public songBecameFrequent(song: Song): void {
        // mark the song as a favourite
    }
}
plantuml Diagram
The same notification, with the compile-time dependency pointing one way.

PlayHistory still calls Playlist at runtime, but at compile time it depends only on PlayObserver, and PlayObserver does not depend on Playlist. The interface does not know which class implements it, so the cycle is broken. PlayHistory can now be tested with a recording observer, a test double like RecordingNotifier.

Cycle Fix 3: Extract a Third Class ​

When the feature belongs to neither class, it can move into a new class that depends on both. This is the right choice when "three plays in a week makes a favourite" is a feature on its own.

typescript
class FavouritePolicy {
    private readonly history: PlayHistory;
    private readonly playlist: Playlist;
    // ...

    /**
     * Marks a song as a favourite if it has been played at least three
     * times in the week ending at the given time. Call it after each play.
     *
     * @param {Song} song the song that was just played.
     * @param {number} playedAt milliseconds since the epoch.
     */
    public songPlayed(song: Song, playedAt: number): void {
        const weekInMs: number = 7 * 24 * 60 * 60 * 1000;
        if (this.history.playsSince(song, playedAt - weekInMs) >= 3) {
            this.playlist.markFavourite(song);
        }
    }
}

PlayHistory loses its back-reference and only has playsSince. Playlist keeps markFavourite and does not know about this feature. The cost is that the code calling play must now also call songPlayed.

In each case, the goal is to make the compile-time dependencies point in one direction, so the dependency graph forms a hierarchy with no cycles. A dependency graph without cycles can be understood one layer at a time, and any class in it can be tested together with only the classes it depends on.

Cohesion and Coupling ​

A concern is a single thing the system must address, such as a rule, a responsibility, or a reason the code might need to change. Separation of concerns is the principle that each concern should be handled in exactly one place in the design. A design can violate separation of concerns in two ways:

  • Tangling occurs when several concerns share one place in the design. The god class from Chapter 11 is tangled. Navigation, history, ratings, and sharing were all mixed together in a single Playlist, so we couldn't read about or change a single concern without caring about them all.
  • Scattering occurs when one concern is spread across several places in the design. The WeeklyRecap we started with was scattered. Knowledge of the play history's representation was not confined to PlayHistory: it was spread across every class that asked for the list of songs in the history. So a single change in representation affected all these user classes.

We detect and fix the problems differently. You find tangling by looking inside one class and noticing several unrelated reasons to change it, and you fix it by splitting the class. You find scattering by making one change and counting the files it touched, and you fix it by giving the concern a single owner with a contract. High cohesion means there is no tangling, and low coupling means there is no scattering. Together they achieve separation of concerns.

How Cohesion and Coupling Affect Each Other

High cohesion tends to produce low coupling. When a class owns one invariant and all the state that the invariant constrains, it can answer questions about that state by itself, and other classes have no reason to reach past it. PlayHistory could offer songsSince because it owned the play history.

Poor cohesion tends to produce high coupling. A class that holds two invariants is used by two sets of collaborators, so its fan-in, the number of classes that depend on it, is higher than it needs to be. Splitting a class in the wrong place causes a different problem. It separates state from the logic that maintains it, and the two resulting classes have to call each other constantly to stay consistent. Two classes that call each other on every operation have increased coupling without improving cohesion.

In Chapter 11, we thought about where the boundaries between classes should be. In this chapter, we looked at these boundaries in more detail and thought about how much communication crosses those boundaries. At a good boundary, everything inside the class serves one invariant, and everything that crosses the boundary goes through a small, stable contract.

When there seems to be a conflict between cohesion and coupling, prefer the design with less communication across the boundary, because communication across a boundary makes future changes expensive.

Judgement Calls ​

It is impossible to completely remove coupling in any non-toy software system. Every collaboration in a design is a dependency, and parts of a system with no dependencies could never work together.

What we tried to understand in this chapter is the difference between necessary and incidental coupling. WeeklyRecap must depend on some source of play history: this is a necessary dependency, and if we tried to remove it, we'd lose functionality. However, WeeklyRecap does not need to depend on how that history is stored, on the class that stores it, or on the chain of objects used to reach it: all of this is incidental coupling.

Like many metrics, trying to optimize for low coupling in isolation from the other design principles can lead to a worse design. Sure, we can reduce coupling to zero by merging all the classes: a class containing the entire program has no coupling between classes at all! But it's probably now a god class, whose issues we dicussed in Chapter 11.

Further, each interface we add adds indirection for future readers of the code: we discussed this abstraction cost at length in Chapter 16. So we have the same advice on where to add this extra indirection: when the dependency is likely to change, when a second implementation is plausible, or when a test needs a stand-in. When a class collaborates with one stable class that no one expects to replace, depending on that class directly is often clearer.

Designing for Low Coupling ​

When a system has low coupling, someone can change its parts without understanding the system as a whole. When each class depends on a small number of stable contracts, the effects of a change have clear limits, and one person can reason about whether the change is safe.

In summary, this chapter described several coding patterns that help us reduce coupling:

  • Ask a neighbour for what you want, instead of going through it to reach another object.
  • Tell an object what you need done, and let it make the decision.
  • Depend on a contract rather than on the class that implements it.
  • Pass only the values an operation needs.
  • Keep dependencies pointing in one direction, and point them at abstractions where change is likely.
Exercise: A Bike-Share Maintenance Report

You have inherited a bike-share system and been asked to extend it.

As a bike-share operator, I want a daily report of the docks that need attention, so that I can send a technician to the right stations.

A Network holds a list of Stations, each Station holds a list of Docks, and each Dock may hold a Bike. A Bike records how many faults it has reported. A previous developer wrote the report like this:

typescript
type Bike = { faultCount: number };
type Dock = { id: string; bike: Bike | null };
type Station = { name: string; docks: Dock[] };
type Network = { stations: Station[] };

class MaintenanceReport {
    /** The network whose docks the report covers. */
    private readonly network: Network;

    /**
     * Creates a report for the given network.
     *
     * @param {Network} network the network to report on.
     */
    public constructor(network: Network) {
        this.network = network;
    }

    /**
     * Lists the docks whose bikes need attention.
     *
     * @returns {string[]} one line per dock holding a bike with more than two faults.
     */
    public lines(): string[] {
        const out: string[] = [];
        for (const station of this.network.stations) {
            for (const dock of station.docks) {
                const bike: Bike | null = dock.bike;
                if (bike !== null) {
                    if (bike.faultCount > 2) {
                        out.push(station.name + " dock " + dock.id);
                    }
                }
            }
        }
        return out;
    }
}

Work through the following:

  1. Map the dependencies. List every type MaintenanceReport depends on, and every fact it assumes about each one. Draw the dependency graph, then use it to identify which of them a change to Bike could break.
  2. Classify the coupling. Using the forms in Degrees of Coupling, name the tightest form present in this code and quote the line that demonstrates it.
  3. Loosen it. The report only needs the docks whose bikes are faulty. It does not need to walk the whole object graph to find them. Redesign the code so that each class answers questions about its own contents, and MaintenanceReport depends on a single interface. Define that interface and write its documentation.
  4. Test it. Write a test double for your interface and a test for the report that constructs no Network, Station, Dock, or Bike.
  5. Judge what remains. Some dependency between the report and the network is necessary. State which parts of the original coupling were necessary for the task and which were incidental. Then justify one dependency that you chose to leave as a direct call on a concrete class.