7

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()
daniel
  • 2,568
  • 24
  • 32
  • Because the second one sometimes looks prettier? – Xymostech Nov 28 '12 at 03:18
  • Many of my professors would have favored the former. They weren't down with returns in the middle of the function/method. http://stackoverflow.com/questions/4838828/why-should-a-function-have-only-one-exit-point – austin Nov 28 '12 at 03:59

1 Answers1

7

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?

Eli Algranti
  • 8,707
  • 2
  • 42
  • 50