patterncsharpMinor
Looping through a collection
Viewed 0 times
loopingcollectionthrough
Problem
In the situation where I am looping through a collection looking for an item, is it better practice to
Return during loop:
Break then return:
break before I return or should I break and then return?Return during loop:
foreach(string item in items)
{
string[] split = item.Split('|');
if(split[0] == searchFor)
return split[1];
}
return null;Break then return:
string result = null;
foreach(string item in items)
{
string[] split = item.Split('|');
if(split[0] == searchFor)
{
result = split[1];
break;
}
}
return result;Solution
Often, the specific problem dictates the solution.
-
Immediately returning can save levels of nested conditions, greatly improving legibility of the code.
-
Waiting until the end allows for simpler logging, and sometimes simpler debugging.
-
If there's a non-trivial probability you'll want to add further logic to the function later, then don't return until the end.
-
Immediately returning can save levels of nested conditions, greatly improving legibility of the code.
-
Waiting until the end allows for simpler logging, and sometimes simpler debugging.
-
If there's a non-trivial probability you'll want to add further logic to the function later, then don't return until the end.
Context
StackExchange Code Review Q#2172, answer score: 4
Revisions (0)
No revisions yet.