DEV Community

Discussion on: A simple tip for cleaner code

Collapse
 
jbristow profile image
Jon Bristow • Edited

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.
def silly(bar):
    output = {"-1": "NO", "0": "MAYBE", "1": "YES"}
    return output[str(cmp(bar,0))]

# LATE EDIT FOR MAXIMUM UNREADABILITY:
def silly(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

Thread Thread
 
joelnet profile image
JavaScript Joel

I think OP's original example uses the conditions == 0, > 0 and < 0, so a hash table wouldn't work for 2 or -2.

Thread Thread
 
jbristow profile image
Jon Bristow • Edited

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)


# python2
def really_silly(bar):
    return ["MAYBE","YES","NO"][cmp(bar,0)]

# python3
def extremely_silly(bar):
    return ["MAYBE","YES","NO"][(bar>0)-(bar<0)]

God, I love how awful python can get sometimes!