Code should only do nothing if nothing is the correct thing to do

Wednesday 10 April 2002This is over 22 years old. Be careful.

This is on my mind, so I’ll share: When writing code, if you want to leave a code path empty (for example, because it’s a placeholder for more code to be written in the future, or because you think it isn’t a case that can arise, or you just don’t feel like writing it), don’t leave it empty.

I’ll state it differently, as a strict rule: Your code should only do nothing if nothing is the correct thing to do.

The reason is this: it is very hard to debug a problem if the root cause is that nothing happened a while back when something should have.

Rather than leave an empty code path, write an assert that expresses your intentions. For example, if you simply haven’t written the code yet, then instead of this:

if (IsThisATrickyFutureCase()) {
    // todo: write some code...
}

do this:

if (IsThisATrickyFutureCase()) {
    // todo: write some code...
    ASSERT(FALSE, "Not yet implemented");
}

Now when the tricky future case finally arrives, instead of nothing happening, and possibly making your whole system behave mysteriously, an assert will be raised, and it will be very clear that some code needs to be written.

Some would claim that leaving these asserts all over is too compulsive. It may be, and there will be plenty of them that are never triggered, or that are removed (to be replaced by real code) a short time later. But, it is not hard to put these asserts in, especially once you get in the habit, and if even one of them fires, it will save you fifteen minutes (or more) of head scratching to figure out how everything got into some “impossible” state.

And if you provide yourself with a rich set of tools ahead of time:

#define NOT_YET_IMPLEMENTED() ASSERT(FALSE, "Not yet implemented")
#define SHOULD_NOT_HAPPEN()   ASSERT(FALSE, "Should not happen")

you can have expressive, strict code with very little trouble. These examples are in C++, where the preprocessor helps a bit, but the same is true in any language: your code should only do nothing if nothing is the correct thing to do.

BTW: I expanded on this in the text section.

Comments

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.