Lesson 5 of 17 · The Forces That Shape Code
Coupling and Cohesion
Two symptoms you've already met
You've felt these before, even if you didn't name them.
The first: you change one line, and something completely unrelated breaks. A test in a feature you haven't touched in months turns red. A queue job that "has nothing to do with billing" starts throwing exceptions because you renamed a field on the user. The change was tiny. The blast radius is enormous.
The second: you open one file to make a small fix, and end up with five other files open, none of which you wanted to read. The model in front of you can't be understood without the trait it uses, the listener it dispatches, the helper it calls, and the global service it quietly depends on. By the time you understand what's happening, you've forgotten why you opened the first file.
Different symptoms, same underlying problem: the joints in the code are in the wrong places. Things that should be apart are stuck together, and things that should be together are scattered.
The two ideas in this lesson, coupling and cohesion, are how we name those joints. Once you have the vocabulary, you can stop saying "this codebase feels weird" and start describing exactly where the seams went wrong.
What coupling actually is
Coupling is how much one piece of code needs to know about another to do its job.
A more useful version: coupling is how much a change in one piece of code forces a change in another.
Two classes that "use each other" are not automatically coupled in a painful way. Everything uses something. The question is: when one of them changes, does the other have to change too? If yes, they're coupled. If no, they're not.
Coupling isn't binary. It's a spectrum. Some kinds are cheap and unavoidable. Some are expensive and worth fighting.
The spectrum, cheap to expensive
Roughly, from cheapest to most expensive:
Coupling on data shape. A function takes a
Userobject and reads$user->email. That's coupling on the shape ofUser. Usually fine. The shape of your domain is supposed to be stable.Coupling on contracts. A class depends on an interface, not on a concrete implementation. The dependency says "I need something that can do X". The class doesn't know who actually does X. Cheap, healthy, easy to change later.
Coupling on concrete classes. A class news up another concrete class directly, or type-hints it directly. Heavier. Now you can't substitute, you can't fake in tests easily, and you've made an opinion about who does the job, not just that someone has to.
Coupling on framework internals. Your business code reaches into how the framework happens to be built today. Eloquent macros, request lifecycle hooks, container internals. The framework upgrades, and your code finds out the hard way.
Coupling on global state, statics, facades, singletons. Two pieces of code don't even appear connected, but they share an invisible state. A change to one ripples through the other in ways no signature reveals. This is the kind of coupling that makes year-three changes terrifying.
Coupling on timing, ordering, and side effects. "This works only because the listener fires before the job is queued. It also only works because the cache is warm by the time the request hits the second route." This is the most expensive kind, because nothing in the code says any of this is true. The contract lives in someone's head.
Most "this codebase is painful" stories are stories about the bottom three.
A small example
A controller posts an order and sends a confirmation email.
Coupled to a concrete:
<?php
declare(strict_types=1);
namespace App\Orders;
use App\Mail\MailgunMailer;
use App\Mail\OrderConfirmation;
use Illuminate\Http\JsonResponse;
final readonly class PlaceOrderController
{
public function __construct(
private MailgunMailer $mailer,
) {}
public function __invoke(PlaceOrderRequest $request): JsonResponse
{
$order = Order::fromRequest($request);
// ...
$this->mailer->send(new OrderConfirmation($order));
return new JsonResponse(['ok' => true]);
}
}Now switch from Mailgun to Postmark. Now write a test that doesn't actually try to talk to Mailgun. Now run the same code from a queue worker that doesn't have Mailgun's SDK loaded. Each of those is a small fight.
Coupled to a contract:
<?php
declare(strict_types=1);
namespace App\Orders;
use App\Mail\OrderConfirmation;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Http\JsonResponse;
final readonly class PlaceOrderController
{
public function __construct(
private Mailer $mailer,
) {}
public function __invoke(PlaceOrderRequest $request): JsonResponse
{
$order = Order::fromRequest($request);
// ...
$this->mailer->send(new OrderConfirmation($order));
return new JsonResponse(['ok' => true]);
}
}The controller doesn't know or care who delivers email. It says "I need a mailer", and somebody else, somewhere else, decides what that means today. Switching providers is a config change. Testing is a one-line fake. Running from a different context is just wiring.
Same job. Same lines, almost. The cost of every future change is different.
What cohesion actually is
If coupling is about how things stick to each other, cohesion is about how the things inside one unit belong together.
The question to ask is short: do these things change for the same reasons?
If yes, high cohesion. The class, file, or module is about one thing. Changes to that thing show up in one place.
If no, low cohesion. The unit is a bag of stuff that happens to share a folder or a class name. Changes to one concern force you to walk through unrelated code on the way.
Cohesion is the property that makes a file feel like it has a point.
Symptoms of low cohesion
You can usually feel low cohesion before you can name it:
The same file changes every sprint, but for completely different reasons. Billing reasons, then auth reasons, then export reasons, then onboarding reasons. The file is "popular" the way a busy intersection is popular.
The class name has an "and" hiding in it, even when it doesn't say "and".
UserManagerisUser and a bunch of stuff someone needed somewhere.A bug in one feature breaks tests for another. The features only share a unit because the unit grew without a theme.
The fat models, fat services, fat controllers everyone has war stories about. Most of those wars are cohesion wars.
New developers can't summarize what a class is for in one sentence. They start the sentence with "well, kind of...".
The single User model that knows about billing, sessions, exports, marketing preferences, audit logs, and team memberships is the canonical low-cohesion class, and often the most expensive file in the codebase to live with.
Low cohesion almost always produces high coupling. When unrelated things share a unit, they get tangled with each other and with everything around them.
Pulling apart a fat class
A small example. Before:
<?php
declare(strict_types=1);
namespace App\Users;
use App\Billing\Invoice;
final class UserService
{
public function register(array $input): User { /* ... */ }
public function authenticate(string $email, string $password): User { /* ... */ }
public function changePassword(int $userId, string $new): void { /* ... */ }
public function chargeMonthlyFee(int $userId): Invoice { /* ... */ }
public function exportAllData(int $userId): string { /* ... */ }
public function updateMarketingPreferences(int $userId, array $prefs): void { /* ... */ }
}Six methods. Three reasons to change living in one file: identity, billing, and personal data. A bug in chargeMonthlyFee and a bug in exportAllData end up in the same git history, the same test file, the same review queue, and probably the same merge conflicts.
After, grouped by reason to change. Each class lives in its own file:
<?php
declare(strict_types=1);
namespace App\Users;
final class UserRegistration
{
public function register(array $input): User { /* ... */ }
}<?php
declare(strict_types=1);
namespace App\Users;
final class UserAuthentication
{
public function authenticate(string $email, string $password): User { /* ... */ }
public function changePassword(int $userId, string $new): void { /* ... */ }
}<?php
declare(strict_types=1);
namespace App\Users;
use App\Billing\Invoice;
final class UserBilling
{
public function chargeMonthlyFee(int $userId): Invoice { /* ... */ }
}<?php
declare(strict_types=1);
namespace App\Users;
final class UserDataExport
{
public function exportAllData(int $userId): string { /* ... */ }
}<?php
declare(strict_types=1);
namespace App\Users;
final class UserMarketingPreferences
{
public function updateMarketingPreferences(int $userId, array $prefs): void { /* ... */ }
}More files. The diff sounds like more code. It almost always isn't, once you account for the helpers that no longer need to live next to unrelated logic.
What you bought:
A billing change touches
UserBillingand nothing else.Tests for one concern don't break when another concern moves.
Different teams, or future you in different moods, can work on different concerns without colliding in the same file.
The next person who reads
UserBillingknows what they're getting before they open it.
You didn't add abstractions or layers. You named the seams that were already there.
This is about change, not aesthetics
It's tempting to read all this as "make pretty code".
The point is that high cohesion plus low coupling means a small blast radius for each change. The thing you want to change has one home. The other things in the codebase don't notice. The cost of change curve stays flatter for longer because each edit reaches less.
Coupling and cohesion are the structural reason the codebase either lasts or rots.
Two traps to avoid
Splitting by type instead of by reason to change. The classic folder layout, Controllers/, Services/, Repositories/, Models/, looks tidy and is almost always low cohesion at the module level. Everything related to billing is scattered across four folders. Everything related to auth is scattered across the same four folders. Each individual file is fine. The system, taken as a whole, has all the wrong joints. Vertical slices, modules, bounded contexts - we'll talk about these in later lessons - are all attempts to fix this.
Over-decoupling. The opposite trap. Every concrete class hidden behind an interface, every interface hidden behind a factory, every factory wired through a builder. "For flexibility." Most of that flexibility is never used, and the indirection costs every reader real time. Couple to a contract when you have a real reason to swap the implementation. Otherwise the concrete class is fine and the interface is noise.
The honest position is the same one we keep landing on. Pick the cheapest joint that solves the problem you actually have: the cheapest one to live with for the next three years, in your context.
The one thing to remember
The codebases that hurt least at year three are the ones where each file has one reason to change and each dependency is honest about itself. That's all "low coupling, high cohesion" really means. Everything else in this course is, in some way, a tool for getting you there.
Related Links
- Coupling and CohesionKent Beck on lowering coupling and raising cohesion to cut the cost of change.
- Balancing Coupling in Software DesignVlad Khononov's book on treating coupling as a design tool with several dimensions.
- Principles of Package DesignMatthias Noback on cohesion and coupling at the class and package level.
- Your Brain on Inversion of Control and Dependency InjectionIoC and DI explained from the ground up.
- Services By LifecycleMichael Nygard on splitting along lifecycle boundaries instead of entity boundaries.