Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

else vs return to use in a function to prematurely stop processing

Tags:

python

[Edit] changed return 0 to return. Side effects of beinga Python n00b. :)

I'm defining a function, where i'm doing some 20 lines of processing. Before processing, i need to check if a certain condition is met. If so, then I should bypass all processing. I have defined the function this way.

def test_funciton(self,inputs):
    if inputs == 0:
        <Display Message box>
        return
    <20 line logic here>

Note that the 20 line logic does not return any value, and i'm not using the 0 returned in the first 'if'.

I want to know if this is better than using the below type of code (in terms of performance, or readability, or for any other matter), because the above method looks good to me as it is one indentation less:

def test_function(self,inputs):
    if inputs == 0:
        <Display Message box>
    else:
        <20 line logic here>
like image 841
mankand007 Avatar asked Jun 25 '12 17:06

mankand007


2 Answers

In general, it improves code readability to handle failure conditions as early as possible. Then the meat of your code doesn't have to worry about these, and the reader of your code doesn't have to consider them any more. In many cases you'd be raising exceptions, but if you really want to do nothing, I don't see that as a major problem even if you generally hew to the "single exit point" style.

But why return 0 instead of just return, since you're not using the value?

like image 60
kindall Avatar answered Oct 04 '22 00:10

kindall


First, you can use return without anything after, you don't have to force a return 0.

For the performance way, this question seems to prove you won't notice any difference (except if you're realy unlucky ;) )

like image 35
Cédric Julien Avatar answered Oct 04 '22 02:10

Cédric Julien