Avoiding Special Cases
Every programming problem has some corner case. Every loop has a first or last element that requires slightly modified processing.
Every time I create a special case in a program, I feel a little bit dirty. I’ve gone ahead and created redundant code. I’ve placed the same logic in two places. When one is changed, the other will break.
###Example
There’s an assignment we’re working on in class that is the epitome of ugly cases. It’s a simple implementation of a Binary Search Tree. Most of the solutions I’ve seen for the *add-node* function involve _three or more_ nested cases and if-blocks, cordoning off various chunks of almost-identical code from each other.
Anyone’s who’s worked with complicated pointer-based structures in C will tell you that this is par for the course.
###Uglyness
But I came up with a really sweet solution. It eliminates special cases _altogether_. It’s a mere 15 lines long.
What’s the drawback? It uses a pointer to a pointer to a structure. Consider the following snippet:
if (compare leftChild);
else
nodeLocation = &((*nodeLocation)->rightChild);
It makes perfect sense to me right now, which is all I need, with the assignment due in a week. But will I still understand this bizarre pointer operation a month from now?
Is it worth the readability tradeoff to have a function with zero redundancy? What if it’s 1/3 the length of the alternative?
For me, I’m pretty sure I’d rather see _less_ code, even if it means reading through the comments to understand a clever hack. And besides, clever hacks give me the [warm fuzzies](http://uwmike.com/archive/programmers-euphoria/).
Mike

Posted at 12:54 am on July 15th by Jeffrey Aho.
Posted at 1:50 pm on July 15th by Mike Purvis.
Posted at 3:18 pm on July 17th by Daniel Dresser.
Posted at 4:14 pm on July 17th by Mike Purvis.
Posted at 6:20 pm on July 22nd by Ryan Hildebrandt.
Posted at 6:18 pm on August 17th by Ian.