Saturday, April 11, 2009

Have Multiple Return Statements

Is having multiple return statement in a method a bad practice ?

We have seen or read in books saying we should have only one exit point for a method. But actually it depends on the case/scenario which we are dealing with. It is proposed to have a single exit point because it will be useful for logging or have some clean up code in one place.

It would be unwise deciding using multiple exit points in many cases, that we are better of returning from a method as soon as it is logically correct to do so.

for example :

public void DoStuff(Foo foo)
{ if (foo == null) return;
...
}

The above code is cleaner than
public void DoStuff(Foo foo)
{ if (foo != null)
{ ...
}
}

So, it is always fine to use multiple exit points where we need not do any logging/ clean up code and in places where it is absolutely logical to do so.

No comments:

Post a Comment