Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice use more that one RETURN statement in a method? [duplicate]

Tags:

c#

asp.net

Possible Duplicate:
Why is it good practice to return at the end of a method

I would like to know if could be considered good practice use several RETURN statements in a method and why. If not, I would like to know how you would rewrite the code in a different way.

public string GetNominativeById(int? candidateId)
        {
            if (candidateId.HasValue)
                return repepositoryCandidate.GetById(candidateId.Value).Nominative;
             else
                return string.Empty;
            }
        }

With one RETURN

 public string GetNominativeById(int? candidateId)
    {
        string result;
        if (candidateId.HasValue)
            result =  repepositoryCandidate.GetById(candidateId.Value).Nominative;
         else
            result =  string.Empty;

        return result;
        }
    }
like image 499
GibboK Avatar asked Oct 02 '12 06:10

GibboK


People also ask

Is it bad practice to use multiple return statements?

It is sometimes said that a method should have only one return statement (i.e. one exit point) and that to code using more than one return per method is bad practice. It is claimed to be a risk to readability or a source of error. Sometimes this is even given the title of the “single exit point law”.

What happens if you have more than one return statement in the same function?

Answer. A function can have multiple return statements but only one of them will be executed because once a return statement is executed, the program control moves back to the caller function skipping the remaining statements of the current function.

Can a method have more than one return?

A method cannot return more than one type. The signature of a method contains the return type or void if the method doesn't return anything. Since it must be defined in the method signature, you must return something of that type.

Why it might be useful to have more than one return?

If a function has multiple points of exit where no more computing should be done, multiple returns has the advantage in my opinion because it is now impossible to perform extra computation after the return statement.


6 Answers

You don't actually need else

string GetNominativeById(int? candidateId)
{
    if (!candidateId.HasValue)  
        return string.Empty;

    return repepositoryCandidate.GetById(candidateId.Value).Nominative;
}

Consider this anti arrow pattern:

if (condition1)
{
    if (condition2)
    {
        if (condition3)
        {
            // code lines
        }
    }
}

the way to return immediately will make your code more readable:

if (!condition1) return;
if (!condition2) return;
if (!condition3) return;

// code lines
like image 86
cuongle Avatar answered Oct 06 '22 01:10

cuongle


No, it's considered bad practice not so good practice to have multiple exit points in a method. It's easier to follow the code if there is a single point of exit.

However, when the method is as small as in the example, it's not hard to follow the code anyway, so having multiple exit points is not really a problem. If it makes the code simpler, you can very well use multiple return statements.

like image 27
Guffa Avatar answered Oct 05 '22 23:10

Guffa


Although you should strive to have only one return statement for readability purposes the are several patterns that involve multiple return statements. One example is Guard Clause.

Example of guard clause:

  public Foo merge (Foo a, Foo b) {
    if (a == null) return b;
    if (b == null) return a;
    // complicated merge code goes here.
  }

Some style guides would have us write this with a single return as follows

  public Foo merge (Foo a, Foo b) {
    Foo result;
    if (a != null) {
      if (b != null) {
        // complicated merge code goes here.
      } else {
        result = a;
      }
    } else {
      result = b;
    }
    return result;
  }

Another case is a switch statement when you might want to return from each case:

switch(foo)
{
   case "A":
     return "Foo";
   case "B":
     return "Bar";
   default:
     throw new NotSupportedException();
}

I would rewrite your code as:

        public string GetNominativeById(int? candidateId)
        {
            return candidateId.HasValue 
                ? repepositoryCandidate.GetById(candidateId.Value).Nominative;
                : string.Empty;
        }

At the end of the day, remember that you (and other developers) will be reading your code many times, so make sure that it's readable and obvious.

like image 31
Jakub Konecki Avatar answered Oct 05 '22 23:10

Jakub Konecki


Take a look at the following Article on Wikipedia. What you're asking is whether you should follow the SESE (single entry, single exit) principle from structured programming.

like image 21
Konstantin Dinev Avatar answered Oct 06 '22 00:10

Konstantin Dinev


One of the rules of Structured programming states that each method should have a single entry and exit point. Having a single exit point (return statement in this case) means any clean up, such as calling Close or Dispose, only needs to happen once. The impact of having multiple exit points is minor on small methods but increases as method complexity increases, where it may be easy to miss a case, or as code as refactored or modified.

like image 42
akton Avatar answered Oct 05 '22 23:10

akton


there is nothing wrong with having more return statement, sometimes it actually help you minify your code and save some unnecessary variable assign like what Cuong Le did pointed out. :D

like image 45
Jerry Lam Avatar answered Oct 06 '22 01:10

Jerry Lam