Special Cases Are a Code Smell
Special Cases Are a Code Smell
In this article, we discuss the importance of eliminating special cases in order to write more effective and generalized code.
Join the DZone community and get the full member experience.Join For Free
A Warning Sign
Los Angeles is famous for its complicated parking signs:They're totems of rules and exceptions, and exceptions to the exceptions. Often, when we code, we forget a lesson that’s obvious in these preposterous signs: Humans understand simple, consistent rules, but fail on special cases.
A Trivial Example
Say you’re given an array of integers, and you want to calculate the sum of each element’s neighbors. Try it:
Before going on, consider how you’d solve this yourself.
A straightforward approach might look like this:
Notice how we treat the endpoints as special cases, complicating the simple rule “sum both neighbors of every element.” A better approach is to first transform the input so the special cases vanish, leaving only the general case. Let’s pad the input with zeros, but loop over the original elements:
Every item now has both a left and right neighbor. The special cases are gone, and the simple algorithm shines through.
You may also like: The Benefits of Learning Algorithms.
Another Simple Example
You start at the bottom (step A) of a 4 step staircase, labeled as follows:
n steps, turning around at the top and bottom. Where do you end up?
If you took 4 steps, you’d finish on step C – 3 steps to reach the top, turn around, 1 step down. Naively, you could simulate this stair pacing: iterate from
n, ping-ponging a current index inside an array.
But, this is inefficient for a large value of
n. Most programmers notice that every 6 steps you return to step A, so the “
n answer” must equal the “
n % 6 answer” (the remainder when
n is divided by
They might solve it like this:
This solution is fast but still contains a needless special case: reaching the top and turning around. Instead, we can “complete the staircase,” viewing the problem like this:
and walk in a single direction, forever. The “top and bottom” special cases disappear. Once again, the code is simpler:
This example is prototypical: Both modular arithmetic and symmetry completion are common techniques when eliminating special cases.
Down With Evens!
Say you’re given an array of arrays, and you want to eliminate even-sized arrays by slicing between the first and second element, like so:
A good first instinct is to use
But the nesting isn’t right: we want the split to produce two elements, not an array containing two elements. You might give up here and use
This would be a shame because conceptually
map is a better fit. Our
map attempt fails because it special cases the even elements, wrapping only those in an array. Instead, let’s wrap odd elements too, and then remove the wrapping from all elements:
This trick takes many forms. Ultimately, avoiding special cases is about making things identical. When you can’t make the special case look general, see if you can make the general case look special.
A Real-World Example
In a system I worked on, merchant hours of operation were stored in a database as bit arrays, and each day was broken into
24 * 12 = 288 5-minute intervals. Here, for simplicity, we’ll use 24 one hour intervals – it won’t change anything relevant.
If a store was open Monday 8am to 1pm, and then again from 2pm to 7pm, our Monday bit array would be:
The goal is to display these bit arrays in a human-friendly form on a web page, the way Yelp does:
01 marks an open time and
10 marks a close time, you might try a solution like this, and think you’re done:
But what if a merchant – a club, say – opens at midnight? The
01 will be missing. Likewise, past-midnight closing times force you to look at the next day:
To display Friday’s hours, for example, we must look at Thursday and Saturday, so we can ignore Thursday’s late-night overflow and correctly report Friday’s 2am closing time.
Again, think about how you’d approach this.
For simplicity, ignore the case where a merchant is open 24 hours straight, but handle all other possibilities. It’s tempting to make special cases for midnight openings and late-night closings. But, can we can avoid them?
Let’s take a full week's schedule and a merchant with both edge cases:
The crucial observation — the rule with no exceptions — is this: the time intervals we display on a given day are exactly those whose left endpoint is contained in that day.
Our algorithm, then, will be:
- Flatten the input so we don’t have to worry about individual days.
- Pad the input so we don’t have to worry about midnight or overflows.
- Zip all valid opening times with all valid closing times.
- Group the results by day, to recover the “day” view.
That’s it — just a couple small adjustments to make our original idea work despite the special cases.
Taking all valid closing times works because ruby’s
zip method ignores extra items by default:
hours we defined above, we’ll combine the tricks we’ve learned so far: modular arithmetic to capture each day’s 24-hour cycle, “padding” the endpoints of the week to make it circular, and modular arithmetic again to handle 24 to 12 hour time conversions.
See the whole thing in action here: Try it online!
Let’s recap what we’ve done. We’ve translated a problem that would require special cases — treating each day’s hours, and the overlaps between them, individually — to one in which all opening and closing times in a week are treated uniformly. In this uniform world, the solution to our problem became trivial: we just zipped together all the opening and closing times.
When we were done, we translated back to our original world of individual days using
group_by. This trick of translating a problem to a simpler “world,” solving it there, and translating it back is common in mathematics and is related to the concept of duality.
Once you start looking for special cases, you’ll see them everywhere. Eliminating them isn’t a minor matter of tidiness, either. It will make your code easier to read, simpler to maintain, and, most crucially, less prone to bugs.
Think of it this way: To make non-trivial code reliable, there are two basic strategies. One is to meticulously enumerate and test all special cases. If you’ve missed any, or if any of your tests are incorrect or incomplete, your code will fail. The other is to recast your problem to make the special cases vanish. There are many fewer ways to fail with the latter strategy. And much less code to maintain.
It’s not always possible to simplify a problem by recasting it. But often it is, if only partially. So, when you find yourself typing
if… stop, and pause for a moment. Look for another solution. It might be simpler than you were thinking.
Here are the utility functions we used in the final merchant hours example:
Opinions expressed by DZone contributors are their own.