I have had a discussion with a coworker about breaking a return
statement and the statement that calculates the return value in two lines.
For example
private string GetFormattedValue()
{
var formattedString = format != null ? string.Format(format, value) : value.ToString();
return formattedString;
}
instead of
private string GetFormattedValue()
{
return format != null ? string.Format(format, value) : value.ToString();
}
Code-wise I don't really see a value in the first variant. For me, the latter is clearer, particularly for methods that short. His argument whatsoever was that the former variant is easier to debug – which is quite a small merit, since VisualStudio allows us a very detailed inspection of the statements, when the execution is stopped due to a break point.
My question is, if it's still a valid point to write code less clear, just to make debugging a glimpse easier? Are there any further arguments for the variant with the split calculation and return
statement?
Best Answer
Introducing explaining variables is a well-known refactoring which can sometimes help to make complicated expressions better readable. However, in the shown case,
Moreover, newer versions of the Visual Studio debugger can show the return value of a function in most cases without introducing a superfluous variable (but beware, there are some caveats, have a look at this older SO post and the different answers).
So in this specific case, I agree to you, however, there are other cases where an explaining variable can indeed improve code quality.