DEV Community

Discussion on: DevTips: Use early returns to avoid nested conditions

Collapse
 
nickholmesde profile image
Nick Holmes

Nice article. Building an intuition for overly complex code is really essential. Often when working on code, there comes that moment when you hack things around to get things working. Its essential to refactor until its been simplified.

Some tool chains can calculate code metrics for you, and Cyclomatic Complexity is very relevant here.

Finally, some languages have support for pattern matching, which can really improve things here. Sorry, I'm not current on Javascript, but your example could be expressed in C# 8 like this;

string render() {
    string personToLookFor = "Thierry";
    (var result, var loading) = doesPersonExists();

    return (result, loading) switch {
        (_, true) => "Loading...",
        (true, _) => $"{personToLookFor} already exists.",
        (_, _)    => $"{personToLookFor} doesn't exist."
    };
}

(You don't strictly need to unpack the tuple, but its more readable)

Collapse
 
yvonnickfrin profile image
🦁 Yvonnick FRIN

Thank you! Really interesting inputs in your comment. Thank you for sharing 🙏

Collapse
 
nikoheikkila profile image
Niko Heikkilä • Edited

Pattern matching can be (sort of) simulated in languages supporting switch cases. I find it very readable.

const render = (person = 'Thierry') => {
    const [result, loading] = doesPersonExists(person)

    switch (true) {
        case loading: return "Loading..."
        case result: return `${person} already exists.`
        default: return `${person} doesn't exist.`
    }
}