returning params from a method
I was wondering which is better style to return a parameter from a method:
1.
if (someBooleanIsTrue)
{
someTypeList = getTypeInstance(开发者_如何学JAVAparam1, param2);
}
else if (anotherBooleanIsTrue)
{
someTypeList = getTypeInstanceSecondMethod(param1, param2);
}
return someTypeList;
2.
List<SomeType> someTypeList = null;
...
if (someBooleanIsTrue)
{
return getTypeInstance(param1, param2);
}
else if (anotherBooleanIsTrue)
{
return getTypeInstanceSecondMethod(param1, param2);
}
return new ArrayList<SomeType>();
Which option do you like better and why? Please have arguments :)
Cheers
It's pretty common for people to tell you that any given method should only return in one place. I find that if methods are kept short and simple then multiple returns aren't as big of a readability issue. The book clean code has a pretty good discussion on the subject of readable code, including this particular topic.
I prefer the 2nd option because the 1st option returns a null value.
When lists are returned chances are that the calling method is going to iterate over the list and in >80% of cases iterating over an empty list when there are no results is exactly the right behavior.
With null you always have to check for the case that null is returned which makes the code and is easy to forget, because it is conceptually different.
I prefer 1) because of the single return path, but I would make this change in case you don't want to return null:
if (someBooleanIsTrue)
{
someTypeList = getTypeInstance(param1, param2);
}
else if (anotherBooleanIsTrue)
{
someTypeList = getTypeInstanceSecondMethod(param1, param2);
}
if (someTypeList == null)
{
someTypeList = new List<SomeType>();
}
return someTypeList;
精彩评论