Lesson 6 of 17 · The Forces That Shape Code
Accidental vs Essential Complexity
The first instinct
Whenever a new feature is being implemented in a product, the developer's first instinct is to implement it as simply as possible, meaning avoiding abstractions at all cost. The code is usually written straight in the controller because the feature doesn't seem very complex yet.
That instinct is fine. Most of the time it's the right call. The trouble starts later, when the feature stops being simple and the code stays where it was first put.
A good way to see this clearly is to follow one feature over time. We'll use a reservation in a hotel booking system as the running example, because almost every product has a feature that looks something like it.
Day one: the simple version
A guest picks a room and a date range, the system creates a reservation. That's it. The first version usually looks something like this:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Illuminate\Database\Connection;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final readonly class CreateReservationController
{
public function __construct(
private Connection $db,
) {}
public function __invoke(Request $request): JsonResponse
{
$reservation = $this->db->table('reservations')->insertGetId([
'room_id' => $request->input('room_id'),
'guest_id' => $request->user()->id,
'check_in' => $request->input('check_in'),
'check_out' => $request->input('check_out'),
'created_at' => now(),
]);
return new JsonResponse(['id' => $reservation], 201);
}
}Eight lines of real work. It does what the customer asked for. It ships quickly. There's nothing wrong with this code on the day it was written.
The team doesn't have coding standards yet. There are no rules about what code goes where. Putting it in the controller is fine, because the whole feature fits in your head and on one screen.
What happens over time
As new features come in, the developers get used to writing code in the controller, since they probably don't have any standards or rules about what goes where. They might be thinking this is just fine for now. It usually is, until it isn't.
Once enough small additions pile up, "create a reservation" is no longer one operation. It's a small workflow, with rules attached to it from every direction. Over time, the same controller has grown into something like this:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Mail\ReservationConfirmation;
use DateTimeImmutable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Database\Connection;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Psr\Log\LoggerInterface;
use Symfony\Component\Lock\LockFactory;
final readonly class CreateReservationController
{
public function __construct(
private Connection $db,
private Mailer $mailer,
private LockFactory $locks,
private LoggerInterface $logger,
) {}
public function __invoke(Request $request): JsonResponse
{
// Validation
$data = $request->validate([
'room_id' => 'required|integer|exists:rooms,id',
'check_in' => 'required|date',
'check_out' => 'required|date|after:check_in',
'coupon_code' => 'nullable|string',
]);
$guestId = $request->user()->id;
// Atomic lock to stop double-booking the same room and date range
$lock = $this->locks->createLock("room:{$data['room_id']}:date:{$data['check_in']}");
if (!$lock->acquire()) {
return new JsonResponse(['error' => 'room is being reserved'], 409);
}
try {
// Reservation business rules
$room = $this->db->table('rooms')->find($data['room_id']);
if ($room->max_nights < $this->nightsBetween($data['check_in'], $data['check_out'])) {
return new JsonResponse(['error' => 'stay too long'], 422);
}
$existing = $this->db->table('reservations')
->where('room_id', $data['room_id'])
->where('check_in', '<', $data['check_out'])
->where('check_out', '>', $data['check_in'])
->exists();
if ($existing) {
return new JsonResponse(['error' => 'room already reserved'], 409);
}
// Pricing and coupons
$nights = $this->nightsBetween($data['check_in'], $data['check_out']);
$price = $room->nightly_rate * $nights;
if (!empty($data['coupon_code'])) {
$coupon = $this->db->table('coupons')->where('code', $data['coupon_code'])->first();
if ($coupon && $coupon->expires_at > now() && $coupon->uses_left > 0) {
$price = match ($coupon->type) {
'percent' => $price * (1 - $coupon->amount / 100),
'fixed' => max(0, $price - $coupon->amount),
};
$this->db->table('coupons')
->where('id', $coupon->id)
->decrement('uses_left');
}
}
// Persist
$reservationId = $this->db->table('reservations')->insertGetId([
'room_id' => $data['room_id'],
'guest_id' => $guestId,
'check_in' => $data['check_in'],
'check_out' => $data['check_out'],
'total_price_cents' => (int) round($price * 100),
'created_at' => now(),
]);
// Confirmation email
$this->mailer->send(new ReservationConfirmation($reservationId));
// Audit log
$this->logger->info('reservation.created', ['id' => $reservationId, 'guest' => $guestId]);
return new JsonResponse(['id' => $reservationId], 201);
} finally {
$lock->release();
}
}
private function nightsBetween(string $checkIn, string $checkOut): int
{
$checkInDate = new DateTimeImmutable($checkIn);
$checkOutDate = new DateTimeImmutable($checkOut);
return $checkInDate->diff($checkOutDate)->days;
}
}It's not just a new reservation in the database anymore. The same handler is now doing:
Request validation
Reservation-specific business rules (max stay length, overlap checks)
Coupon application and price calculation
Sending emails
Atomic locks to stop race conditions
Audit logging
And other things that will need to be added in the near future
Every one of those was a small, sensible addition. Each one was easy to write the day it was added. None of them, on its own, felt like a big enough deal to refactor for. The controller grew because growing the controller was always the cheapest move on the day.
The developers aren't being careless. They're creating what's called accidental complexity anyway, one reasonable addition at a time. The code becomes harder to maintain, bug-prone, and demotivating to work with.
Two kinds of complexity
There are two completely different reasons a piece of code is hard.
The first is that the problem itself is hard. A reservation system that has to honor room capacity, time-zone-aware availability, recurring stays, multi-property access rules, and rate plans (the different prices and conditions attached to the same room) is not going to be a one-liner no matter how clean the code is. There's a floor of difficulty that comes from the world the code is trying to model.
This is essential complexity. It comes from the domain. You can move it, organize it, name it. You can't make it disappear.
The second is that the code itself made the work hard. Validation, persistence, pricing, locking, emailing, and logging all live in the same method, sharing variables, sharing failure modes, sharing review cycles. The actual problem is moderate. The way it's expressed makes it big.
This is accidental complexity. It's complexity we added on the way. The problem doesn't need it. The code chose to have it. With effort, it can be removed.
It's not only code
Accidental and essential complexity are true not just for code, but also for team processes, tools, frameworks, and infrastructure.
A standup that drifted from fifteen minutes to fifty is accidental. A deploy pipeline that takes forty minutes because nobody trimmed it for two years is accidental.
The same diagnostic applies to all of them: is the difficulty coming from the world the team is operating in, or from choices the team made on the way?
This lesson focuses on code, but the habit of asking "is this essential or accidental?" pays off in every part of how a team works.
Why the team can't see it
The hardest thing about accidental complexity is that the team that created it usually can't see it.
Each addition was reasonable on the day it was made. Each one passed review. Each one shipped. By the time the file is painful to work in, the team has lived with it for so long that it feels like the natural shape of the problem. "Reservations are just complicated." Sometimes they are.
Three things keep the team from seeing it:
Familiarity. You stop noticing pain you've adapted to. The 600-line controller is fine because you know where everything is.
Sunk cost. Every line in there was paid for. Pulling it apart feels like throwing work away, even when the alternative is throwing time away on every future change.
No vocabulary. Without the words "accidental" and "essential", it's all just "complex code". You can't argue for the work to fix it because you can't describe what you'd be fixing.
Naming the two kinds is most of the cure.
How to avoid the accidental kind
Avoiding accidental complexity in long-term business software takes more thinking and planning, and usually more code up front. That's the price of keeping the shape simple as the system grows.
That sounds backwards, and it is, on the day. Writing extra code today, in exchange for a simpler shape later, is a hard trade to make under deadline pressure. It's also the trade that pays off after year two.
A small preview of what "extra code, simpler shape" looks like for the reservation example. The controller shrinks to a translation step: turn the validated request into a command, hand it to a handler, turn the result into a response.
<?php
declare(strict_types=1);
namespace App\Reservations\CreateReservation;
use Illuminate\Http\JsonResponse;
final readonly class CreateReservationController
{
public function __construct(private CreateReservationCommandHandler $handler) {}
public function __invoke(CreateReservationRequest $request): JsonResponse
{
$result = $this->handler->handle(new CreateReservationCommand(
roomId: $request->integer('room_id'),
guestId: $request->user()->id,
stay: $request->stay(),
couponCode: $request->validated('coupon_code'),
));
return new JsonResponse(['id' => $result->reservationId], 201);
}
}The handler is the new home for the sequence of steps. It coordinates and decides nothing on its own.
<?php
declare(strict_types=1);
namespace App\Reservations\CreateReservation;
use App\Reservations\Coupon\Coupon;
use App\Reservations\Room\Room;
use App\Reservations\Room\RoomLock;
use Illuminate\Contracts\Events\Dispatcher;
final readonly class CreateReservationCommandHandler
{
public function __construct(
private RoomLock $lock,
private Dispatcher $events,
) {}
public function handle(CreateReservationCommand $command): CreateReservationResult
{
return $this->lock->around($command->roomId, $command->stay, function () use ($command): CreateReservationResult {
$room = Room::findOrFail($command->roomId);
$coupon = Coupon::findRedeemable($command->couponCode);
$priceCents = $room->priceFor($command->stay);
$priceCents = $coupon?->applyTo($priceCents) ?? $priceCents;
$reservation = $room->reserve($command->stay, $command->guestId, $priceCents);
$coupon?->redeem();
$this->events->dispatch(new ReservationRequested($reservation->id, $command->guestId));
return new CreateReservationResult($reservation->id);
});
}
}The rules that used to be inline conditions in the controller now live on the model that owns them. The room knows how long a stay it allows and which dates it already has taken.
<?php
declare(strict_types=1);
namespace App\Reservations\Room;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Stay;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Room extends Model
{
public function reservations(): HasMany
{
return $this->hasMany(Reservation::class);
}
public function priceFor(Stay $stay): int
{
return $this->nightly_rate_cents * $stay->nights();
}
public function reserve(Stay $stay, int $guestId, int $priceCents): Reservation
{
if ($stay->nights() > $this->max_nights) {
throw new StayTooLongException($this, $stay);
}
if ($this->reservations()->overlapping($stay)->exists()) {
throw new RoomAlreadyReservedException($this, $stay);
}
return $this->reservations()->create([
'guest_id' => $guestId,
'check_in' => $stay->checkIn,
'check_out' => $stay->checkOut,
'total_price_cents' => $priceCents,
]);
}
}The pieces not shown each hold one concern. CreateReservationRequest validates and hands back a Stay value with the two dates and a nights() method. RoomLock holds the lock for the duration of the callback and releases it on the way out. The two exceptions render themselves as the 422 and 409 responses the old controller built by hand, so nothing catches them. The expiry and uses-left checks on coupons sit behind Coupon::findRedeemable(), and the percent-versus-fixed match moved onto Coupon::applyTo(). The confirmation email and the audit log are listeners on ReservationRequested, so a third side effect means a new listener, not an edit to the handler.
A test for "a stay longer than the room allows is refused" now needs a room and a stay. It doesn't need a lock, a mailer, a coupon, or an HTTP request.
The total line count goes up. The number of files goes up. The complexity in any single file goes way down, because each file has one reason to change. We'll get to these patterns later in the series. For now, just notice the shape of the trade.
Design patterns, principles, coding standards, and shared rules help here, as long as everyone actually follows them. It takes discipline. Early on, it slows the team down. After enough practice, it stops slowing them down at all, because the patterns become the default and the simpler shape becomes the easy thing to write.
Essential complexity is normal
The bigger the product complexity is, the harder it is to work on such products. That's normal. This is essential complexity, and we can't really avoid it. It's the nature of the business.
Tax rules across twelve countries are hard. Pricing models with three tiers, regional rules, partner overrides, and a five-step approval flow are hard. Reservation systems that have to honor recurring stays, group bookings, and integrations with three channel managers (the systems that sync availability and pricing out to booking sites) are hard. None of that is the developer's fault. It's the world the product lives in.
How to tell which is which
A few questions that usually surface the answer:
Can a domain expert explain why this is hard? If yes, it's probably essential. If they're confused by your explanation, it's probably accidental.
Would a different framework, language, or layout remove the difficulty? If yes, accidental. If no, essential.
If you started over from a blank repo with the same product requirements, would this complexity show up again? If you can imagine a credible blank-repo version that doesn't have it, it's accidental.
Does the difficulty live in code that touches the real domain (reservations, rate plans, availability), or in plumbing (factories, managers, dispatchers, providers)? Domain-shaped difficulty is usually essential. Plumbing-shaped difficulty is usually accidental.
None of these are perfect. Together they're enough to make a call most of the time.
What to do with each kind
For essential complexity:
Make it visible. Give it a name in the code. A class called
RoomAvailabilityPolicybeats a few lines hidden in a controller.Contain it. The fact that pricing is complex is no reason for the rest of the app to be. Put the hard parts behind a clear boundary, and let the rest of the system stay simple.
Test it directly. Essential complexity is where bugs hide. Tests written in the language of the domain keep the rules honest.
Don't apologize for it. If the world demands it, the code is allowed to demand it. Hiding real difficulty behind a fake-friendly API is a way of lying to the next reader.
For accidental complexity:
Notice it. This is the hardest step. Most accidental complexity is invisible to the team that wrote it because they've adapted to it.
Remove it when it's cheap to remove. The earlier you catch it, the cheaper it is to take out.
When it's expensive to remove, contain it. Wrap it in a smaller boundary, stop adding to it, and let new code grow around the simpler shape.
Resist replacing it with new accidental complexity. Swapping a "Manager" pattern for ports and adapters, in a feature that nobody else integrates with, hasn't fixed anything. It's redecorated.
The architecture follows the context
Choosing a specific architecture, set of patterns, and principles depends on the context the application is in, in order to tame the system's essential complexity. It shouldn't be done because someone told you to do it without understanding your context.
A reservation system for a five-room boutique inn and a reservation system for a global chain of three hundred hotels are not the same problem. Both can use the word "reservation" in the database. Almost everything else about how the code should be shaped depends on which context you're in.
Vertical slices and domain modeling come later in this course. CQRS and event-driven flows come later in the series. All of them are tools for taming essential complexity in specific contexts. They make some things easier and some things harder. The job is to know which ones earn their place in the situation you're actually in.
What this isn't
It's not a permission slip to delete everything you don't immediately understand. Some accidental-looking code is essential complexity in disguise, named badly. Removing it without understanding why it's there leads directly to the bugs the original author was trying to avoid.
It's also not an argument that essential complexity is good. It's just real. The work is to live with it cleanly, not to pretend it's a virtue.
The one thing to remember
The complexity you can remove is worth more attention than the complexity you can't. It's tempting to spend the energy the other way around: suffering through accidental complexity as if it were a law of nature, and trying to refactor essential complexity as if it were a mistake.
Get this one habit: when you meet a piece of pain in the codebase, before you do anything else, ask which kind it is. The answer changes everything you do next.
Related Links
- No Silver BulletFred Brooks's 1986 essay that introduced essential and accidental complexity.
- Out of the Tar PitMoseley and Marks on why most software difficulty is accidental, caused by state and control flow.
- Simple Made EasyRich Hickey's talk on the difference between simple and easy.
- A Philosophy of Software DesignJohn Ousterhout on complexity as the root problem in software design.