Should I return from a function early or use an if statement?

  • I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

    public void SomeFunction(bool someCondition)
    {
        if (someCondition)
        {
            // Do Something
        }
    }
    

    or

    public void SomeFunction(bool someCondition)
    {
        if (!someCondition)
            return;
    
        // Do Something
    }
    

    I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

    I'm a bit late for this discussion so I won't put this in an answer; I also thought about this two years ago: http://lecterror.com/articles/view/code-formatting-and-readability I find the second easier to read, modify, maintain and debug. But maybe that's just me :)

    There is an unstated assumption in the question's examples and in the answers that we are not considering early return from within loops. They can make reasoning about a function a good deal more complicated, and are harder to brush off as being a harmless convenience.

    now this question is a fine example of an opinion-based question

    so what if there is no absolute proof in one or another direction? When enough argumentation is provided in one and another direction and there is a voting if the answer is correct - it makes it very useful. I find closing questions like this to be harmful to the value of this site.

    And I like opinion based questions and answers. They tell me what majority prefers and that lets me to write the code for others to read.

    1- Mostly it's **opinion-based** & personal flavor preference 2- It depends on **what the function returns**, for example: A- if function always return a number (or always return an string, or always return a boolean, or doesn't return anything) then multi-exits might be better, B- but if function returns an object (or an array, or different return type for each condition) then nested IFs might be better/easier

    I really don't know why this is closed. Don't come back with a list of guidelines, caz if this closed because it violate guidelines, then the guidelines needs to change.

  • I prefer the second style. Get invalid cases out of the way first, either simply exiting or raising exceptions as appropriate, put a blank line in there, then add the "real" body of the method. I find it easier to read.

    Smalltalk calls these "guard clauses". At least that's what Kent Beck calls them in Smalltalk Best Practice Patterns; I don't know if it's common parlance.

    Not in Delphi though right? I was under the impression that "Exit" was considered harmful.

    @Peter: Hmm? I don't think I've heard that before in the Delphi community. Do you have any links?

    @Mason, you'd know better than me. My Delphi community consists of people who call it "Delphee". It just seems like Result := something; Exit; isn't so good looking, therefore it's bad. Just a prejudice though.

    @Peter: Well, if it makes it look any better, since D2009 we've had the ability to write `Exit(value);` instead of making it two statements. :)

    RE: Delphi Exit's http://stackoverflow.com/q/1021498/1765 answers are about 3/4 in favor of exit/pragmatism.

    I'm not sure what happened with my earlier comment - feel like I walked into the wrong bar or something. Surprised nobody flagged my comment for abuse :}

    Exiting early allows you to pop stuff off your limited mental stack. :)

    I've previously heard this referred to as "the Bouncer Pattern" - get rid of bad cases before they get in the door.

    I'd even go as far and say this definitely is the ONLY right thing to do.

    Plus you don't keep adding indents if you get rid of the border cases at the beginning.

    And some coding standards still require a Single Exit... :(

    Throw exception? Yes. Early exit? Not so much.

    The problem with this is that when you overlook a possible bad condition for your following code, your codes gets executed nonetheless. If, on the other hand, you only execute your code when the correct conditions are met (first example in OP), then you do not have to fear the unknown. Therefore I choose the first example as the best, imo.

    Correction to my previous comment: I am wrong of course, because the if-condition will evaluate to true too when I forget to add the necessary condition checks, so my preferred way isn't any different from my not preferred way.

    I like this way, as well. It allows filtering down the amount of code to run to only the cases where all conditions are met. I usually use this in public methods to filter out invalid cases, then call an internal method to actually run the code for relevant matches.

    what if I have nested if statements and also nested if in else conditions. Then how I will exit from the all if statements.

    @klaar, "The problem with this is that when you overlook a possible bad condition for your following code, your codes gets executed nonetheless." - you are totally wrong here. Examples from OP have totally equivalent logic since it uses absolutely same `someCondition`. Please read again before you state such a nonsense.

    Talking about reading again, please read my comment following the wrong comment. I already know, thanks.

    Just a personal preference but if an entire function will be skipped based on a condition, I'd prefer to guard in the calling function. If multiple/complex condition checks are made, I'd extract the entire condition check into a separate function entirely.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM