A few weeks ago I wrote about Boolean Parameter Elimination, using function pointers to reduce the number of branches in a function. The same method could also be used eliminating switches. Let’s have a look at an example of a function switching on an enum parameter:
void pointMove(Point *point, Direction direction, int step)
{
switch (direction) {
case NORTH:
point->x += step;
break;
case SOUTH:
point->x -= step;
break;
case EAST:
point->y += step;
break;
case WEST:
point->y -= step;
break;
default:
assert(0);
}
printf("Point: x=%i, y=%i\n", point->x, point->y);
}
The function pointMove operates on a Point struct changing its coordinates based on a cardinal direction enum parameter. After a direction specific instruction has been executed a common instruction, in this case printf , is executed for every direction.
Extracting Functions
An initial simple improvement to this would be extracting functions for each case:
void pointMove(Point *point, Direction direction, int step)
{
switch (direction) {
case NORTH:
pointMoveNorth(point, step);
break;
case SOUTH:
pointMoveSouth(point, step);
break;
case EAST:
pointMoveEast(point, step);
break;
case WEST:
pointMoveWest(point, step);
break;
default:
assert(0);
}
pointPrint(point);
}
Each block of code in the switch is now extracted into a function. The common code at the end has also been extracted:
static void pointMoveNorth(Point *point, int step)
{
point->x += step;
}
static void pointMoveSouth(Point *point, int step)
{
point->x -= step;
}
static void pointMoveEast(Point *point, int step)
{
point->y += step;
}
static void pointMoveWest(Point *point, int step)
{
point->y -= step;
}
void pointPrint(Point *point)
{
printf("Point: x=%i, y=%i\n", point->x, point->y);
}
The example here is of course kept very simple with only one instruction per case in the switch. It is sadly not uncommon to see code where each case in the switch contains tens or even hundreds of lines of code. In this simple example the code complexity after the change is roughly the same with each case still containing one line. For more complex functions this restructuring is the least one should do.






