tags:

views:

195

answers:

3

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?

+8  A: 

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
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
A: 

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
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
+1  A: 

This is already answered. Multiple exit points are fine and very useful!

Marcin Gil