Basically I have a series of logic in my website that can lead to 5 total outcom
ID: 652338 • Letter: B
Question
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?
Explanation / Answer
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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.