06 May, 2010

Conditions: No Need for Extra "else"

Sometimes when I am writing code quickly and jumping between functions, I miss a bit obvious logic and end up having multiple "else" statements. Below are two examples doing the same thing. Here the logic itself is not important, this is just to make a note.
...
   if trueKey != "":
       modObj = pkgDict[trueKey]
       if modObj.__dict__.haskey(className):
           return modObj.__dict__[className]
       else:
           return None
   else:
       return None 

In above example, two else conditions are unnecessary and messy. Concise version,
...
    if trueKey != "":
        modObj = pkgDict[trueKey]
        if modObj.__dict__.haskey(className):
            return modObj.__dict__[className]

    return None 

2 comments:

  1. That's cool. But you could take it one step further. Some claim it's not good to have multiple return statements in a function. Especially so when they appear in nested ifs. They might be hard to spot when revising code and you stand the risk of ending up in a branch with no return. If you instead initiated a default value to return and modified this as needed you could have a only single return statement, at the very end.

    One disadvantage with this method though is that it will be slower as it does atleast one or two assignments.

    ...
    result = None
    if trueKey != "":
    modObj = pkgDict[trueKey]
    if modObj.__dict__.haskey(className):
    result = modObj.__dict__[className]

    return result

    ReplyDelete
  2. yes you are absolutely right. I actually prefer one return statement. My initial code is generally spontaneous so I miss some good coding practices. That's why I had multiple else.

    ReplyDelete