Software Engineering

Code Entropy: Why Clean Code Does Not Stay Clean

Most codebases do not become hard to work with because of one bad decision. They get there through hundreds of small, defensible ones. This is code entropy, the tendency of code to lose its structure as it changes.

A small example

Suppose an application calculates VAT at checkout. A second feature, invoicing, needs the same figure, and copying one line is the fastest way to ship:

// checkout.php
$total = $subtotal * 1.16;

// invoice.php
$total = $subtotal + ($subtotal * 0.16);

Both are correct today. When the rate changes, someone must find every copy, and written differently, they are hard to search for. Miss one and the invoice stops agreeing with the checkout. The fix costs a few minutes when done early:

function with_vat(float $subtotal, float $rate = VAT_RATE): float
{
    return round($subtotal * (1 + $rate), 2);
}

The new function also forces a useful question that the copies hid: how should the amount be rounded?

The usual causes

  • Inconsistent style. When similar problems are solved in different ways, readers must work out whether the difference matters.
  • Duplicated logic. A bug fixed in one place survives in the others.
  • Deferred refactoring. New features get added around old structures instead of through them.

What it costs

Reading comes first: developers spend more time working out what code does than changing it. Then debugging slows, because a symptom in one module has its cause in another. Finally, every change carries a risk of breaking something unrelated, so people stop making improvements at all.

What works

  1. Refactor as part of the change. Improve the code you are touching. A separate cleanup phase rarely survives the next deadline.
  2. Automate style. A formatter and linter in CI end the arguments and keep reviews focused on substance.
  3. Review for design. Ask whether this duplicates something, and whether the next person will understand it.
  4. Test before refactoring. Tests are what make restructuring safe. Characterization tests can pin down existing behaviour in code that has none.

One caution: do not remove every duplicate on sight. Two pieces of code that look alike but change for different reasons should stay separate. A wrong abstraction costs more than a small repetition.

Code entropy is one part of a wider problem described in why software falls apart.

Tell us what your organization needs.

Describe the requirement and the constraints you are working within. We will assess it and advise candidly on whether and how we can help.

Discuss a Project