4

Basically I have a series of logic in my website that can lead to 5 total outcomes. Basically two different if tests and then a catch all else statement.

For example:

if cond1:
    if mod1:
        #do things
    elif mod2:
        #do things
elif cond2:
    if mod1:
        #do things
    elif mod2
        #do things
else:
    #do things

I was thinking about rewriting it like this:

if cond1 and mod1:
    #do things
elif cond1 and mod2:
    #do things
elif cond2 and mod1:
    #do things
elif cond2 and mod2:
    #do things
else:
    #do things

Is there any real difference in these two coding options/a better choice for this kind of logic testing?

3
  • 2
    Pick whatever is more readable and maintainable to you.
    – user22815
    Aug 15 '14 at 16:18
  • 1
    You may want to post your actual code, because it might be that you should get rid of those conditional statements anyway (for example by replacing them by inheritance). Aug 15 '14 at 16:30
  • 3
    These snippets are not equivalent. The first snippet will not execute any of the #do things lines when either cond1 or cond2 is true, but neither mod1 or mod2 is true. However the second snippet will execute the final else clause. Aug 18 '14 at 1:54
8

One difference is that cond1 only gets evaluated once in the first code snippet, but can get evaluated twice in the second example if mod2 is false. If cond1 has side effects, that changes the semantics. If cond1 is expensive to evaluate, that could also be a problem even if the semantics don't change.

If neither of those conditions are true, it's largely a matter of taste and style, but I'd argue the second form more clearly highlights the nature of the logic (5 independent cases) whereas the first form requires a bit more effort to see that the 5 cases can be treated separately.

1
  • 1
    but see Kelly Thomas' comment above: the two blocks are not equivalent, even if all the conditions are simple variables. Aug 20 '14 at 17:29
0

Nested if statements (or nested anything) adds complexity to the code. It makes it harder for someone to read and understand the code. There is actually a complexity measurement called Cyclomatic complexity. The way it works is each time there is a conditional branch it adds one point. Higher points means more complex. There are some automated tools that can scan your code and score it for you.

One of our primary jobs as Developers is to decrease the complexity as much as possible. I try to avoid nested blocks when possible so your second choice looks like a good way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.