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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
scroll top