Code Rage

Saturday, July 17, 2004

Size Matters: Code should be as big as it is important.

I recently code reviewed a body of code that was driving me crazy, not because of any particular bug, but because I found the style grating. I have a rule of thumb that I try to stick to when programming: "Code should be as big as it is important." What do I mean by that? The first example of grating code:

int
foo(VARIANT_BOOL a)
{
boolean a ;

if ( a == VARIANT_TRUE )
{
b = true ;
}
else
{
b = false ;
}

return theActualWorkhorseOfThisFunction(b) ;
}

I find it ridiculous that the majority of the function is taken up doing a trivial translation from VARIANT_BOOL to boolean (one that should probably be unnecessary in the first place, but that's another issue.) Here's my take on it:

int
foo(VARIANT_BOOL a)
{
boolean b = (a == VARIANT_TRUE) ? true : false;

return theActualWorkhorseOfThisFunction(b);
}

A lot of people tend to shy away from the trinary operator, perhaps because they think it leads to some gnarly code. But in the above example, the trivial act of assigning a boolean value has been reduced to a trivial size.

There was a second bothersome construct that I spotted during the code review:

switch (a)
{
case FOO1:
// deliberately empty
break;

case FOO2:
//deliberately empty
break;

case FOO3:
//deliberately empty
break

case FOO4:
someFunction();
someOtherFunction();
break;

default:
//deliberately empty
break;
}

But reducing the size of the unimportant code makes the code more readable, because you focus in on the important case:

switch (a) {
case FOO4:
someFunction();
someOtherFunction();
break;

case FOO1:
case FOO2:
case FOO3:
default:
break; // deliberately empty;
}