Search code examples
if-statementreturncode-structure

if-else or early return


Sometimes I like to use early return statements to prevent nesting if statement, which I find makes for less readable code.

I am wondering if there is any objective or overwhelming general consensus as two which of the following patterns is better practice? I don't think this is a subjective question, since what I am really asking is there a near objective preference.

void func() {
    if (a) {
        do b
    }    
    else {
        do c
    }
}

or

void func() {
    if (a) {
        do b
        return;
    }

    do c
}

Solution

  • The first is better. Simply put,it helps another developer to understand that c compiles because the condition is false. It also prevents other people from making damaging changes to your code. That said,they are both correct and would both work just fine