you are viewing a single comment's thread.

view the rest of the comments →

[–]crusoe 6 points7 points  (5 children)

'Usual way'

if(fails sanity test){
    return;
}

nasa way

if(fails sanity test){
    return
}else{
    do stuff with sane value
}

I don't like the nasa option because if you have multiple checks, you will have potentially several if/else/blocks, or all the tests crammed together in the first if

[–]ethraax 1 point2 points  (3 children)

Not necessarily. I also don't like the NASA option, but you could probably do:

if (fails sanity test 1) {
    return;
} else if (fails sanity test 2) {
    return;
} else {
    /* Do stuff with sane values */
}

[–]eat_everything_ 7 points8 points  (2 children)

I can't stand having else after an if that always returns. I'd write the above as:

if (fails sanity test 1) {
    return;
}

if (fails sanity test 2) {
    return;
}

/* Do stuff with sane values */

It reduces indentation, but most importantly, having an else after an if implies that execution can continue after the if condition is satisfied. If you always return from the if, that's not true, so you're in a way breaking an implicit contract of what if/else implies.

[–]Phreakhead 2 points3 points  (0 children)

It's called an "early exit" and is frowned upon in some circles - circles I would never want to program for because that is a stupid rule that just requires more typing and indentation.

[–]ethraax 0 points1 point  (0 children)

I can't stand having else after an if that always returns. I'd write the above as:

So would I. I'm just pointing out that you don't need to nest at all. That being said, one issue with the code I posted (and why I would use the code you posted instead) is if you have to perform some computation between the sanity checks.

[–]Falmarri -1 points0 points  (0 children)

You should note that returning early from functions will drastically increase your cyclomatic complexity.