Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverted if-statements

Tags:

coding-style

Is there a particular reason to favor stepping into multiple blocks vs. short cutting? For instance, take the following two functions in which multiple conditions are evaluated. The first example is stepping into each block, while the second example short cuts. The examples are in Python, but the question is not restricted to Python. It is overly trivialized as well.

def some_function():
    if some_condition:
        if some_other_condition:
            do_something()

vs.

def some_function():
    if not some_condition:
        return
    it not some_other_condition:
        return
    do_something()
like image 293
daniel Avatar asked Nov 28 '12 03:11

daniel


People also ask

How do you reverse an if statement in Python?

Position the caret over an if-else statement. Press Alt+Enter. From the pop-up menu, select Invert if-else statement.


1 Answers

Favoring the second makes code easier to read. It's not that evident in your example but consider:

def some_function()
    if not some_condition:
       return 1
    if not some_other_condition:
       return 2
    do_something()
    return 0

vs

def some_function():
    if some_condition:
       if some_other_condition:
           do_something()
           return 0
       else:
           return 2
    else:
        return 1

Even if the function has no return value for the "failed" conditions, writing the functions with inverted ifs way makes placing breakpoints and debugging easier. In your original example where would you place the breakpoint if you wanted to know whether your code is not running because some_condition or some_other_condition failed?

like image 103
Eli Algranti Avatar answered Sep 29 '22 16:09

Eli Algranti