July 31, 2011
Clean Code Helps Prevent BugsAnother quick thought-dump for the weekend.
In his papers on OO design principles, Uncle Bob Martin uses the terms "rigid" and "brittle" to describe code that's hard to change and easy to break.
It probbaly needs rearticulating that there's a direct relationship between those two things: that is, code can be easy to break for the same reasons that it is hard to change.
When we look at factors that make code harder to change, we can see how this might be so.
The readability, or comprehensibility, of code is one obvious common factor. Modifying code we don't understand is a bit like performing keyhole surgery wearing dark glasses - the capacity for unwitting mistakes is significantly higher.
Complexity is another. There's no doubt that code that is more complex tends to be buggier, and the reason for this is simple: more complex code is more likely to be wrong because there are more ways for it to be wrong. Just as we're more likely to throw a seven when rolling a pair of dice, we're more likely to make a mistake when rolling complex code. The exponential explosion of logical combinations of wrong code very quickly overpowers the slow, linear growth of correct combinations. It's basic probability.
Duplication also adds scope for more errors. In particular, it adds a risk that when we need to change common, duplicated logic, we overlook one of the duplicates, leading to inconsistencies and contradictions in our code.
Unmanaged dependencies can also make code more likely to be defective. the risk that a change to one part of the software will inadvertantly cause another part (or parts) to break is magnified significantly when there are more dependencies along which effects can propogate.
If our code is simpler, more comprehensible, low in duplication and organised to minimise the "ripple effect" of changes, it will tend to be less buggy. So we should view Clean Code as not just an enabler of change, but as an aid to defect prevention.
Posted 7 years, 7 months ago on July 31, 2011