I am using Python for my example, but my question is referring to programmming languages in general.
def some_function(eggs):
if eggs == 1:
do_something_1()
elif eggs == 2:
do_something_2()
elif eggs == 3:
do_something_3()
else:
do_error()
return
do_something_4()
do_something_5()
do_something_6()
(This is just an example. My functions will not be called do_something_x.)
Would putting a return in the else like this be a bad programming practice? Would it be a better idea to put
do_something_4()
do_something_5()
do_something_6()
in each of the if/elifs?
The main issue I see with your code is that the error case is hidden more than half way down the function body. It makes the code difficult to read. Since what you are doing is validating the arguments to the function, you should do that first.
My preference in the case of an invalid argument is to raise an appropriate exception such as
ValueError. Without knowing what your function does, or whatdo_errordoes, it’s hard to say with absolute certainty that this applies to your case. But generally, getting incorrect arguments isn’t something a function can recover from. The caller gave the arguments; so put the onus on the caller to recover from that error.Also, here’s an idiom you can use to avoid long lists of
elifs: