Tom Ritchford
2 min readMay 20, 2024

--

Your rule is sometimes true and sometimes false. "It depends".

The general consensus is that each control structure adds some logical complexity and the more logical complexity there is in a small space, the harder it is for a programmer to understand it. There are measures of this like https://en.wikipedia.org/wiki/Cyclomatic_complexity.

A Python ternary statement adds a moderate amount of complexity to a statement, but most statements are already fairly complex. A lot of the time, this will be too much.

And yet consider return table[default if x is None else x].

Expanding this to three or four lines with an if statement is not an improvement.

And sometimes there are dozens or even hundreds of mutually independent conditions.

I once refactored a long routine, a maze of if-elses, into this one long expression:

return (
some_boolean * ['some', 'list']
+ some_condition(x) * ['other list', 'list']
+ other_condition(x, y, z) * ['hello', 'there'] +
# 40 more of this
)

Yes, you the reader will have to think a bit at that first line. And you're right, it's bad to have to think about details like that, I don't deny it! It wastes the time you should be spending on business logic. Code should read like prose.

But in this case, you see the idea fairly fast, and then the rest of the code is obvious, and (the key part) making small changes is obvious, too, even if you've never seen the code - either change an existing condition, or add a new one.

No one had done anything wrong with the initial code, it started with four conditions, but time elapsed and it was 60 or 70, and errors from interacting conditions happened more than once...

--

--