When negative evaluation in if clause will cause a return
call inside a function/method, what is more recommended in Python, to nest the if clauses or to utilise the inverse evaluation and call the function return? e.g.:
if required_condition_1:
if required_condition_2:
if required_condition 3:
pass
return 'error for condition 3'
return 'error for condition 2'
return 'error for condition 1'
Or:
if not required_condition_1:
# preparation...
return 'error for condition 1'
if not required_condition_2:
# preparation...
return 'error for condition 2'
if not required_condition_3:
# preparation...
return 'error for condition 3'
# if runtime reaches this point it means that it has passed all conditions
Imagine you have to register a user, and you need various conditions to be satisfied. User will only be registered if they are all satisfied, but error messages depend upon what condition fails.
My guess is that in other circumstances, as a user mentions in the answers section, other actions could apply if a certain condition fails. Then I think I should nest the ifs. However, I will only be returning an error message, so I think the second option is preferable.
I have also thought about assertion:
try:
assert(required_condition_1)
try:
assert(required_condition_2)
# do tasks
except AssertionError:
# error for condition 2
except AssertionError:
# error for condition 1
Even though I think this last way is not pretty recommendable as in treating exceptions. Also as an SO user mentions:
If the code is correct, barring Single-event upsets, hardware failures and such, no assert will ever fail. That is why the behaviour of the program to an end user must not be affected. Especially, an assert cannot fail even under exceptional programmatic conditions. It just doesn't ever happen. If it happens, the programmer should be zapped for it.
I know this might seem primarily opinion-based, but for me it is not since all languages have style guidelines that produce a more sustainable, scalable and readable environment depending on its characteristics and functionalities. I would like to know what if there is a recommended way of treating this matter inside methods and most importantly, why.