Special cases aren't special enough to break the rules
Published by Beto Dealmeida on
My thoughts on special cases in programming
If you're not familiar with the Zen of Python, by Tim Peters, type import this
on an interpreter:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
I have a corollary to rule #8:
Every time you fix a bug with an
if
condition, you're hiding an underlying architectural problem.
When we're working on a problem (or a ticket) it's easy to get tunnel vision, and only see the conditions that make the bug appear. There's an old joke where a person went to the doctor and said:
— Doctor, every time I press my stomach it hurts.
— Then stop doing it!
It's a similar thought process when working on a bug: "when these conditions occur, this will break". That thought is easily translated directly into a solution, going from:
do_something() # breaks if `these_conditions`
To:
if not these_conditions:
do_something() # no longer breaks
While this might fix the problem at hand (and close the ticket!), there are a few problems with this:
- It might not fix other related problems. What if the conditions are slightly different, will the code still break?
- It might break expectations, if this part of the code is one of many components of a bigger system. We now have one component that behaves slightly different depending on the input conditions.
- It might hide underlying architectural problems. A good design has to deal with as few special cases as possible. Can the system be redesigned so that the
if
condition is no longer needed?
Conditions sure have their place in code, but my suggestion is to ask yourself these questions every time you want to add an if
to solve a bug. And remember that special cases usually aren't that special.