Tuesday, October 10, 2006

Readable Code

I think, to structure your code readably, you have to partition your code into different levels. Perhaps the different levels are written in different languages, perhaps not. The top level is the business level. At this level, you should be speaking a mostly declarative language and should be side effect free. Your code should be straightline. The second level is the logical level. At this level, you can have conditions and iterations and anything in the first level. The third level allows anything in the second level plus side effects. Finally, the fourth level allows comparative and arithmetic operations plus anything in the third level. The interesting thing to note, I believe, is that side effects are more readable than comparative and arithmetic code. Of course, it could be that comparative and arithmetic code is less useful than side effect code, so it is pushed to a lower level.

Let's look at an example:

extern int debug;

void foo()
{
int i;
for(i = 0; i < 100; ++i)
{
if(debug)
{
printf("%d\n", i);
}
}
}

This is a level 4 function. It has side effects, comparisons, etc... Let's try to turn it into a full 4-tiered function (yes, you wouldn't do that to something like this, but just for example.)

// level 1 - straightline
void foo()
{
print_numbers_to(100);
}

//level 2 - conditions
void print_numbers_to(int count)
{
if (in_debug())
loop_to(count, print_integer);
}

// level 3 - side effects
void print_integer(int i)
{
printf("%d\n", i);
}

// level 4 - comparisons
int in_debug()
{
return debug == 1;
}

// level 4 - side effects
void loop_to(int count, void (*func)(int))
{
int i;
for(i = 0; i < count; ++i)
{
func(i);
}
}

See how much better that is?