Wednesday 27 June 2012

How I broke the code

One of my favourite coding analogies is Uncle Bob's Boy Scout Rule - "Always leave the campground cleaner than you found it". I try to apply this rule when I have the drains up on a piece of code, if it looks like it needs some love.

I got bitten today, when a piece of boy scouting I'd done hit production. With hindsight it was obvious that I should have taken more care, but the trapdoor I fell down was a humdinger.
The code I thought I was refactoring was similar to this:
So I added some basic optimisation:
All good...
Except, the code I actually refactored to ended up looking like this:
Can you spot the difference? I didn't! It's subtle, but the effect was a huge change in behaviour.
I've learnt lots from this:
  • tiny refactors can have a huge effect;
  • code will sometimes come back and bite you;
  • a peer review is not a safety net;
  • you can't guarantee a refactor unless you have solid unit tests;
  • don't assume that code you're about to refactor is in any way optimal;
and, most important
  • when a ticket comes in around some code you've changed, grab it

No comments:

Post a Comment