Messy Code Is Bad Code
My apartment is a mess. After a party on Saturday there are glasses, pizza boxes, dirty dishes, empty bottles and bottle caps scattered in every corner of my place. Some might ask: “Why don’t you just clean it?” Well, I’m a procrastinator. As long as I can open the window and nothing smells too bad, hey life can go on, right?
Code, however, doesn’t have an aroma that you can smell to know it has gone bad. You can trip over it though if you leave it messy. Checking code in that has poor variable naming or doesn’t space correctly will bite you the next time you try to edit it or the next time someone tries to read it. For example:
int blah;
cin >> blah;
int tmp = 1, tmp2 = 0, tmp3;
for(int i=1; i < blah; i++ )
{cout << tmp2 << ", ";
tmp3 = tmp; tmp += tmp2; tmp2 = tmp3;} // Do it!
Really, what does this code even do? At first glance you can’t tell, which is a bad sign.
Messy code isn’t just badly formatted code either. It could be code that you know could be written better, but you write it to be quick and dirty because you want it to just work:
// calculate
double rate = amount / time; // TODO, div by 0?
if( rate > 1.0 )
{
cout << "Got it!";
}
else
{
// figure this out later
}
If this code finds its way into the shipped product, you’re in trouble. It’s not that TODOs are bad, TODOs can be a good thing and you should always mark code that is not complete with a TODO. You just have to remember to go back and finish them off. Use assertions for cases that you haven’t handled, that way these cases don’t get forgotten:
// calculate
assert( fabs( time ) > EPSILON );
double rate = amount / time; // TODO, div by 0?
if( rate > 1.0 )
{
cout << "Got it!";
}
else
{
// TODO, figure this out later
assert( false );
}
An even more robust method for catching unfinished TODOs is to search the code base sometime before you ship and evaluate whether any particular ones need to be fixed.
Development Process
My coding process usually goes like:
1. Make it work by any means necessary
2. Make it work the right way
3. Fix the code up to be acceptable for check-in
4. Make sure it works fast enough
For me, seeing the solution in any form helps me formulate a more permanent solution. Knowing how your preferred development process works will help you in catching messy code. I know I can’t check in code that hasn’t gone through at least step 3, and most of the time step 4 (depending on what I’m working on).
It’s not important that you spit out polished code on your first try, writers don’t write masterpieces without spell check and several revisions. Do what you have to do to get the job done so long as the end result meets the quality bar. But don’t be tempted to check in messy code, or the inconspicuous “well formatted polished turd”. It’s better to do it right the first time then have to deal with the smell of rotten work that has been left to sit for too long, because it will catch up with you.
Speaking of which, it’s time to open another window…