3

Possible Duplicate:
Should a function have only one return statement?

A fellow programmer asked me why should we always return at the end of a method?

We had both be taught to always have only a single return statement in a method and not multiple scattered throughout the code.

Any good reasons for this?

Community
  • 1
  • 1

2 Answers2

21

There is a school of thought that says that you should have a single point of entry, and a single point of exit. If you have more, you should refactor the code to be clearer.

I don't subscribe to that thought though, and frequently use guard clauses, like this:

public void DoSomethingOnMales(Person p)
{
    if (p.Sex != Sex.Male)
        return;
    ....
}

Of course, you should still try to limit the number of returns, as too many of them, though not bad in and of themselves, is a good indication that you've got a complex method and should probably try to simplify it.

Lasse V. Karlsen
  • 350,178
  • 94
  • 582
  • 779
  • 2
    Good rules of thumb, so +1. In my opinion, a return at the end of a function is just the default case, and depending on the type of the function, an early return is either an error (as in your guard conditions) or it is an early success (i.e. when searching for something). – OregonGhost Apr 02 '09 at 08:04
1

You can return at any time, it doesn't have to be at the end of the method. The only thing to watch out for is that you don't have any unreachable code: code that will never be reached because you always return before it is reached.

If you are worried that you may confuse yourself, causing you to make mistakes, by returning before the end of a method, then avoid it. I however don't hesitate to use return statements where-ever I want, because it can be useful.

thomasrutter
  • 104,920
  • 24
  • 137
  • 160
  • 1
    With modern compilers, you don't have to worry if you have unreachable code, because the compiler will tell you (at least the C# compiler). – OregonGhost Apr 02 '09 at 08:03
  • Resharper seems to favor multiple returns over nesting. for instance an IF statement which would return a value or null gets turned into IF something return null; and another return outside the IF statement with the value. – Ruben Verschueren Sep 20 '16 at 08:27
  • You can, but you can also use GOTO, they are just as bad as each other. – Quentin 2 May 14 '18 at 07:34
  • `goto` has a greater ability to create confusing code than `return`, as `return` is limited to just jumping to the end of the function, whereas `goto` can jump anywhere in the function, including into a control structure. Edit: unless c# restricts this. – thomasrutter May 15 '18 at 00:50