· software-development c

Returning from methods

When pair programming there are obviously times when you have different opinions about how things should be done.

One of these is the way that we should return from methods. There seem to be two approaches when it comes to this:

Exit as quickly as possible

The goal with this approach is as the title suggests, to get out of the method at the earliest possible moment.

The Guard Block is the best example of this. It is generally used at the start of methods to stop further execution of the method if the parameters are invalid for example:

1
2
3
4
5
~~~
public void DoSomething(SomeObject someObject)
{
   if (someObject == null) return;
   // Do some other stuff
}~~~
When used in this way it is very similar to what would be called a pre condition in the world of Design by Contract. It can also be used in methods which return a result:
1
2
3
4
5
~~~
public SomeObject GetSomeObject()
{
   if(ThisConditionHappens()) return new SomeObject(thisParameter);
   return new SomeObject(thatParameter);
}~~~
In this example there are only two execution paths so returining early is fine. When there start to become a lot of different branches, however, the idea of returning in each place becomes counter productive and makes the code harder to read.

If that becomes the case, however, there’s probably greater things to worry about with regards to the method than how best to return the result!

Return everything at the end

This approach is fairly self explanatory too. If my somewhat contrived example was written to return everything at the end it would look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
~~~
public SomeObject GetSomeObject()
{
    SomeObject someObject = null;
    if(ThisConditionHappens())
    {
        someObject = new SomeObject(thisParameter);
    }
    else
    {
        someObject = new SomeObject(thatParameter);
    }
    return someObject;
}~~~
This idea starts to come into its own when there are more possible paths of execution, although if this becomes the case it might be better to use the collecting parameter idiom to solve the problem.

Just in case it hasn’t come across, I am a big advocate of the idea of returning early from methods as it means I don’t have to understand the whole internals of a method if I only care about one branch.

If a method gets into such a state that returning early becomes unreadable this would be a clear sign to me that the method is doing too much and should be refactored into smaller chunks.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket