daniel
daniel

Reputation: 2626

Inverted if-statements

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()

Upvotes: 7

Views: 10101

Answers (1)

Eli Algranti
Eli Algranti

Reputation: 9007

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?

Upvotes: 7

Related Questions