views:

76

answers:

3

I found some code like this in a project I'm working on

public SqlDataReader SomeMethod(int someParam)
{
      // ... some code goes here
      SqlDataReader dataReader = m_command.ExecuteReader(CommandBehavior.CloseConnection);
      return dataReader;
}

I was wondering what is better, the original or below

public SqlDataReader SomeMethod(int someParam)
{
      // ... some code goes here
      return  m_command.ExecuteReader(CommandBehavior.CloseConnection);
}

Is there any advantage to creating the variable and then returning it as opposed to just returning the created reader? I would think no as it's just a reference. The example I give was what I found but it could be any variable type. One thing I can think of is during debugging, it's probably nice to look at what's in the variable.

Anybody like to contribute their 2 cents?

+2  A: 

Debugging is probably the best reason. With the first way, it's easier to e.g. check if dataReader is null before returning it.

There really shouldn't be a performance difference, as you said. If this method is invoked often, the JIT compiler (if enabled) is very likely to optimize the local variable away.

Michael Myers
But at least for the CLR, you don't have an option of turning off the JIT.
MichaelGG
This is tagged language-agnostic, so I didn't want to make my answer C#-specific. The code could be valid Java, too.
Michael Myers
A: 

I agree that it is nicer for debugging to have the variable defined. However, there are many studies showing that lines of code are directly related to number of bugs.

In general, it really doesn't matter too much.

Zack
A: 

Any half-decent compiler will optimise the first example such that dataReader doesn't need to be stored in a temporary variable. In other words, both examples should have the exact same efficiencies.

Personally, I prefer the second (shorter) example as splitting that line over two lines doesn't simplify reading at all.

marcog