Air Filters & Clean Code

29. February 2016 Uncategorized 0

This weekend I took my wife’s truck in to get some new tires. While at the store, they did a multi-point inspection. They called me to tell me I needed a new air filter. I turned down their offer to replace it (they wanted $50.)  Today, we were driving and her “Check Engine” light came on.  I took it by the parts store to have them run the code. The code indicated it could be one of a few things, the easiest thing to do was to replace the air filter. So I bought the $13 air filter and came home to replace it.  When I popped the hood to replace the filter, I saw a hose that runs off the main hose from the air filter, and it had popped out of its connector. It’s most likely that the loose hose caused the problem, although it did need a new air filter.

As I thought about this, I thought it was a good illustration for clean code.

Why?

The only way to know if an air filter is dirty and needs replacement is to look at it. (At least in the type of cars I buy. Maybe in the high end cars there’s a sensor that tells you, but not in ours.) To do this, you have to take the cover off the filter, move a couple hoses around, pull out the filter and see if it’s dirty.

What happens when you need to fix a bug or add a feature in the code?  You have to read the code that’s already there. Imagine that the code you have is like my wife’s car. In order to really get at what it’s doing, you have to dive into functions and look at each one until you know what’s going on.  You finally diagnose the problem and put in code to fix it. But, like with my wife’s car, you knocked loose a hose or two.  You don’t notice it right away because the code isn’t that clean. It’s hard to read. But a day or two after release you start seeing things in production that don’t look right.

When you pop the hood (i.e. go through the source control history) you see you accidentally deleted a line of code that was necessary.

Now, imagine your code was clean and readable. You have tests that tell you what is happening (and with some analysis, what isn’t happening.)  You’d be able to jump in and implement the right fix pretty easily.

It would be like if my wife’s truck had an air filter sensor. The mechanics would not have had to move hoses around causing a check engine light to come on.