Explicit Over Implicit: More Code Is Better

I’m looking for examples to use as examples (e.g. “lists of names, lists of animals, simple math equations, etc..”). Turns out, it’s hard to look up sets of examples for coding without getting examples of coding1. That’s fine, even if it’s a little meta.

During my search I found this post titled Coding Best Practices.

The bullet points make sense. Use consistent indentation, follow the DRY principle, etc… But, I side-eyed the “Keep The Code Simple” example2. It says this:

def numbers_are_in_range(*, a, b, c):
    if a < 0 and b > 0 and c == 0:
        return True
        return False

should be written like this:

def numbers_are_in_range(*, a, b, c):
    return a < 0 and b > 0 and c == 0

Fewer lines? Sure.

Simpler? Not so much.

That code is harder to understand.

Implicit returns (like the second snippet) take more brain power to deal with than explicit ones (like the first example)3. In this case, you know at a glance that the first snippet will return one of two possible values: True or False. In the second snippet, you have to mentally walk through the formula to reason out what the possibilities are.

You don’t notice the effort when you’re writing the initial code. The context is already in your head. It’s every other time we use it that we’ll feel the impact. We spend infinitely more time in the future working on our code than when we first write it. It’s in our best interest to make things as clear (and as explicit) as possible for our future selves.

Equating fewer lines with simpler code is an easy mistake to make. But, it’s not always the case. Don’t be afraid of those extra lines when they add clarity. They’re your friends.

  1. I’ve realized that I can go to the wonderful exercism.io for examples of examples.

  2. Yep. I translated the example into python functions. And, while I don’t want to get into it in this post, I wonder if there’s not be a cleaner way to code the conditional as well as.

  3. Don’t just take my word for it. The Zen of Python’s second line is literally:

    Explicit is better than implicit.


Random Related Links