I’m fine with the quick return for validation or a guard as long as it’s right at the beginning of a function.
I’d rather have one single exit point for my function though since having multiple outs adds to the chances that someone will add code between the two exits without realizing it.
A “better” solution:
# python 2 only. Cmp was taken from the code golfers in python 3.defsilly(bar):output={"-1":"NO","0":"MAYBE","1":"YES"}returnoutput[str(cmp(bar,0))]# LATE EDIT FOR MAXIMUM UNREADABILITY:defsilly(bar):return{"-1":"NO","0":"MAYBE","1":"YES"}[str(cmp(bar,0))]
If your function is equivalent to a nested ternary, then that’s a good use of early return. Anything more complicated needs to have the contents of the If statements extracted into methods to more clearly show off your now ternary equivalent ifelse
Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
I’m fine with the quick return for validation or a guard as long as it’s right at the beginning of a function.
I’d rather have one single exit point for my function though since having multiple outs adds to the chances that someone will add code between the two exits without realizing it.
A “better” solution:
If your function is equivalent to a nested ternary, then that’s a good use of early return. Anything more complicated needs to have the contents of the If statements extracted into methods to more clearly show off your now ternary equivalent ifelse
I think OP's original example uses the conditions
== 0
,> 0
and< 0
, so a hash table wouldn't work for2
or-2
.I think if you look closer, you'll see that my solution is equivalent in output to the OP's example.
Here's a nastier one (also with a py3 equivalent)
God, I love how awful python can get sometimes!