Special Cases Are a Code Smell

By Jonah Goldstein.

LA Parking Sign
LA Parking Sign

Los Angeles is famous for its complicated parking signs:

Sunny 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:

 1 3 4 5 0 1 8 --- | 3 --+ 

Before going on, consider how you’d solve this yourself.

A straightforward approach might look like this:

Try it online!

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:

 0 1 3 4 5 0 1 8 0 --- --- | | +-- 3 --+ 

Every item now has both a left and right neighbor. The special cases are gone, and the simple algorithm shines through.

Try it online!

Another simple example

You start at the bottom (step A) of a 4 step staircase, labeled as follows:

 ____ | D ____| O | C |< ____| / \ | B ____| A 

You take 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 1 to n, ping-ponging a current index inside an array.

But this is inefficient for large 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 6).

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:

 ____ | D | ____| |____ O | C C | |< ____| |____ / \ | B B | --> wrap ____| |____ around A 

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 wish to eliminate even-sized arrays by slicing between the first and second element, like so:

A good first instinct is to use map:

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 reduce:

Which 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 the 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:

12am 8am 1pm 7pm 11pm v v v v v 0 0 0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0

The goal is to display these bit arrays in human friendly form on a web page, the way Yelp does:

Simple Hours
Simple Hours

Since 01 marks an open time and 10 marks a close time, you might try a solution like this, and think you’re done:

Try it online!

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:

Late Night Hours
Late Night Hours

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.

 5pm 1am 5pm 1am 5pm v v v v v 000000000000000001111111110000000000000001111111110000000000000001111111 \______________________/\______________________/\______________________/ Thurs Friday Saturday

Again, think 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 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:

  1. Flatten the input so we don’t have to worry about individual days.
  2. Pad the input so we don’t have to worry about midnight or overflows.
  3. Zip all valid opening times with all valid closing times.
  4. 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:

Using the 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.

Take Aways

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.

Additional Notes

Here are the utility functions we used in the final merchant hours example: