Coder Perfect

To reduce nesting, invert the “if” expression.


For example, when I ran ReSharper on my code:

    if (some condition)
        Some code...            

ReSharper issued the warning above (Invert “if” statement to reduce nesting) and suggested the following fix:

   if (!some condition) return;
   Some code...

I’m curious as to why it is the case. I’ve always believed that using “return” in the midst of a method, like “goto,” was problematic.

Asked by Lea Cohen

Solution #1

It is not only pleasing to the eye, but it also reduces the method’s maximum nesting level. This is often seen as a positive because it makes procedures more understandable (and indeed, many static analysis tools provide a measure of this as one of the indicators of code quality).

On the other side, it allows you to have many exit points in your technique, which some people believe is a bad idea.

In my opinion, ReSharper and the first group are correct (in a language that has exceptions I find it silly to discuss “multiple exit points”; almost anything can throw, so there are numerous potential exit points in all methods).

In terms of performance, both variants should be equivalent in every language (if not at the IL level, then at the very least once the jitter is done with the code). This is theoretically dependent on the compiler, however nearly any commonly used compiler nowadays is capable of considerably more advanced code optimization instances than this.

Answered by Jon

Solution #2

A return in the middle of a method isn’t always a bad thing. If returning quickly clarifies the code’s intent, it might be preferable. Consider the following scenario:

double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
            else result = normalPayAmount();
     return result;

If _isDead is true in this situation, we can exit the procedure immediately. Instead, it might be better to organize it like this:

double getPayAmount() {
    if (_isDead)      return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired)   return retiredAmount();

    return normalPayAmount();

This code was selected from the refactoring catalog. Replace Nested Conditional with Guard Clauses is the name of this refactoring.

Answered by jop

Solution #3

This is a bit of a religious debate, but I agree with ReSharper that less nested is preferable. I believe that the benefits of having numerous return pathways from a function outweigh the disadvantages.

The major purpose for reducing nesting is to make code more readable and maintainable. Remember that your code will be seen by a lot of other developers in the future, and code with less indentation is generally easier to understand.

Preconditions are a fantastic example of where returning early at the start of the function is acceptable. Why should the presence of a precondition check affect the readability of the rest of the function?

Concerning the drawbacks of returning from a method several times, debuggers are now quite powerful, and it’s extremely easy to figure out exactly where and when a function is returning.

Having multiple returns in a function is not going to affect the maintainance programmer’s job.

It will be due to a lack of readability in the code.

Answered by LeopardSkinPillBoxHat

Solution #4

There shouldn’t be a performance hit, as others have said, but there are other factors to consider. Aside from those legitimate worries, this can expose you to traps in some situations. Let’s pretend you’re dealing with a duplicate:

public void myfunction(double exampleParam){
    if(exampleParam > 0){
        //Body will *not* be executed if Double.IsNan(exampleParam)

In comparison, consider the ostensibly equivalent inversion:

public void myfunction(double exampleParam){
    if(exampleParam <= 0)
    //Body *will* be executed if Double.IsNan(exampleParam)

So, in some cases, what looks to be a correctly inverted if may not actually be.

Answered by Michael McGowan

Solution #5

The concept of just returning at the end of a function dates back to before exceptions were supported in programming languages. It allowed programs to include cleanup code at the conclusion of a method and be confident that it would be called and that another programmer wouldn’t hide a return in the method, causing the cleanup code to be skipped. A memory or resource leak could occur if cleaning code is skipped.

However, it makes no such promises in a language that enables exceptions. Any statement or expression can generate a control flow that causes the method to end in a language that allows exceptions. This means that cleanup must be done with the finally or keywords.

Anyway, I’m arguing that I believe many people cite the “only return at the conclusion of a method” rule without understanding why it was ever a good idea, and that decreasing nesting to enhance readability is definitely a better goal.

Answered by Scott Langham

Post is based on