If/then style question

Grant Edwards invalid at invalid.invalid
Fri Dec 17 12:31:17 EST 2010


On 2010-12-16, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Thu, 16 Dec 2010 21:49:07 +0000, John Gordon wrote:
>
>> (This is mostly a style question, and perhaps one that has already been
>> discussed elsewhere.  If so, a pointer to that discussion will be
>> appreciated!)
>> 
>> When I started learning Python, I wrote a lot of methods that looked
>> like this:
>> 
>>   def myMethod(self, arg1, arg2):
>>     if some_good_condition:
>>       if some_other_good_condition:
>>         if yet_another_good_condition:
>>           do_some_useful_stuff()
>>           exitCode = good1
>>         else:
>>           exitCode = bad3
>>       else:
>>         exitCode = bad2
>>     else:
>>       exitCode = bad1
>>     return exitCode
>
>
> It doesn't look like you were learning Python. It looks like you were 
> learning C with Python syntax :(

Let's not blame C for bad program structure.  No good C programmer
would use that construct either.

One choice in C would look like this:

  if (some_condition)
    return code1;

  if (other_condition)
    return code2;

  if (condition3)
    return code3;

  //do whatever work really needs to be done here.

  return successCode;

Or, if there's cleanup that needs to be done, then you "raise a an
exception":


  if (condition1)
    {
      ret  = code1;
      goto errexit;      
    }    

  if (condition2)
    {
      ret  = code2;
      goto errexit;      
    }    

  if (condition3)
    {
      ret  = code3;
      goto errexit;      
    }    
    

  // do the normal bit of work


  errexit:

  //cleanup  

  return ret;

  
-- 
Grant Edwards               grant.b.edwards        Yow! Awright, which one of
                                  at               you hid my PENIS ENVY?
                              gmail.com            



More information about the Python-list mailing list