mardi 31 mars 2020

Explicit or implicit else after conditionals succeed?

I often have methods in my APIs that have conditionals prior to performing the work intended. These checks (normally) raise an exception specific to the API (not user generated such as providing a string to a method using a float). They take the following form:

if condition_1:
    raise APIException('Msg 1')
elif condition_2:
    raise APIException('Msg 2')
...
elif condition_n:
    raise APIException('Msg n')
else:
    # do work

The conditionals are all able to be completed prior to any work and never depend on it being done prior. If any exception is generated during the else portion, its because of improper method use.

After looking at these methods and seeing this structure throutout my APIs, I've begun to wonder if this is a stylistic approach problem or not? That is, should I keep it this way where its explicit that the else portion means "all checks have passed now begin" or remove it thus making it implicit:

if condition_1:
    raise APIException('Msg 1')
elif condition_2:
    raise APIException('Msg 2')
...
elif condition_n:
    raise APIException('Msg n')
# do work

Further, given that each conditional suspends function execution prior to the work, is the if-elif stack another stylistic approach problem? That is, should I just use if or keep elif:

if condition_1:
    raise APIException('Msg 1')
if condition_2:
    raise APIException('Msg 2')
...
if condition_n:
    raise APIException('Msg n')
# do work

From the Zen of Python, I would say keeping if-elif-else is "Explicit is better than implicit" so this may answer itself, but from a idiomatic standpoint, does successive if vs if-elif really alter the readability/maintainability of the code? It does imply multiple conditions may happen simultaneously, which is why I prefer the if-elif because only one causes the function to suspend. I don't believe any of these forms alter performance.

Aucun commentaire:

Enregistrer un commentaire