Please Do Not Use "else"
Posted on Tue, 29 Jan 2019 in Python
I don’t like else
if there is return-statement in both branches. It is always possible to write code without that unnecessary if
appendage. Such code looks more accurate, more clear and it is easier to read. Why so many developers still use this useless else
?
Reviewing my colleagues’ code I noticed that he can improve it omitting else
. In response, he gave me a link to PEP8 where if-else
with return
noticed as a possible variant. His code looks like this:
def get_magic_number(use_magic):
if use_magic:
return calculate_with_magic()
else:
return calculate_with_science()
For a machine this code is perfect. It does what it should do. But I, as human, care about readability. And I always, in this case, stop reading and ask myself:
- What does this function return?
- Are both return-statements reachable with any input?
Even such short functions manage me to stop and think. But not always they are so simple and short.
So I have a question, why we can’t omit else
? I think profit is obvious:
- Code becomes one-line shorter.
- Less intend for one of the branches.
- We get a default return-statemen for a function.
def get_magic_number(use_magic):
if use_magic:
return calculate_with_magic()
return calculate_with_science()
Is it more readable? Yes, it is. Is there any difference for an interpreter? No, it isn’t. So why do we use this useless construction where it is not necessary? PEP8 and I-will-need-it-later are not the arguments.
What do you think? Is this all just matter of taste?
Got a question? Hit me on Twitter: avkorablev