Simon Forman wrote:
Hey I was hoping to get your opinions on a sort of minor stylistic
point.
These two snippets of code are functionally identical. Which would you
use and why?
The first one is easier [for me anyway] to read and understand, but
slightly less efficient, while the second is [marginally] harder to
follow but more efficient.

## First snippet

if self.higher is self.lower is None: return
if self.lower is None: return self.higher
if self.higher is None: return self.lower

## Second snippet

if self.higher is None:
    if self.lower is None:
        return
    return self.lower
if self.lower is None:
    return self.higher

What do you think?

Explicit is always better, `return None` when that is your intent. `return` shouts to the reader, "I want to get out of this function now, and no one cares about the return result."

Personally, I only use the one-liner if/else clauses if it's an extremely trivial condition, and even then, usually not there. (The only place I use it consistently is `if __name__ == '__main__': main()`.) If it's part of something more important that needs inspection -- as this obviously does given the questions you've had about it, doesn't skip space. Newlines are free.

Even when expanding about the first test, there's no reason to do chained `if`s. One `if` with an `and` works just fine.

Paul Rubin's looked to be the best overall replacement, as the logic here looks strangely turned inside out. You're obviously looking for which one _isn't_ `None`, so write the tests that way. It's much easier for everyone else (including your potential future self) to follow.

--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis
  They are ill discoverers that think there is no land when they can
   see nothing but sea. -- Francis Bacon
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to