Thursday, August 23, 2007

Each line of code should do one thing

I was writing some code today that looks like this:

int counter = 0;
while (/* some condition */)
{
// Do some formatting
counter++;
FormattingProcessStatus(counter);
}

Now I could have done it differently like so:
int counter = 0;
while (/* some condition */)
{
// Do some formatting
FormattingProcessStatus(++counter);
}

which would have "saved" me one line of code. I hate this - I always have. Ever since I started learning C/C++ (over a decade ago) and while trying to solve an exercise discovered a situation where two different compilers generated different results. But today, for the first time, I understood why I hate it so much - it's against a very basic rule that EACH LINE OF CODE SHOULD DO ONE THING.



This is a very simple rule I don't remember having read anywhere, but it's the basis for readable code. Writing code, and even more so - reading code, requires a lot of brain effort. You need to be able to see the whole architecture, and how that particular object and method fits in. Sometimes you need to keep a whole stack of variables (state) in mind to really understand what's going on, etc. The difference between having to read a line that does one single thing and reading a line that does more - is very big, and complicates the reading of the code exponentially.


So if you want your code to be readable - start by making sure each line does exactly one thing!

No comments: