News for hackers. Stuff that matters.
Re:Anti-If: The missing patterns (2016) by joshuamorton on Wednesday June 27, 2018 @04:11PM (#17411416)
There's a reason the pattern is referred to as "exiting early". Another description might be using guards. Basically, you shouldn't do this if you're doing something complex Basically you can imagine each of the if statements being a "guard" against an condition that might cause you to exit early. This becomes much clearer if you have multiple such clauses, and add the mental note that each conditional should contain only a return statement with a single expression.

    function foo(bar) {
        if is_null(bar) {
            return TypeError
        }

        if !validate_input(bar) {
            return ValueError
        }

        if cached(bar) {
            return cache(bar)
        }

        // Added as a workaround for client XYZCorp since...
        if (bar == "A special value) {
            return "A special result"
        }

        return do_a_complex_thing_to(bar)
    }
You could equivalently structure it as a bunch of else ifs, but there's no real reason to do it that way.

There are no comments on this comment yet.