HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Is this a valid loop?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisloopvalid

Problem

I have the following code:

private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find)
{
   foreach (ScatterViewItem svi in classScatterViews)
   {
      if ((svi.Tag as SourceFile).Equals(find))
      {
         return svi;
      }
   }
   return null;
}


Now I'm asking myself if this is valid or if I should better use:

private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find)
{
   ScatterViewItem result = null;
   foreach (ScatterViewItem svi in classScatterViews)
   {
      if ((svi.Tag as SourceFile).Equals(find))
      {
         result = svi;
         break;
      }
   }
   return result;
}


Is there any common practive which one to use? And are both loops doing the same?

Solution

First one is hundred times better then the second one. I would avoid defining a variable if you don't really need to. Also I don't believe in one return methods. Especially I don't believe that they improve readability.

LINQ would definitely improve it:

return classScatterViews.FirstOrDefault(v => v.Tag.Equals(find));


Also I would not use as operator if I do not check result for null.

Code Snippets

return classScatterViews.FirstOrDefault(v => v.Tag.Equals(find));

Context

StackExchange Code Review Q#1156, answer score: 22

Revisions (0)

No revisions yet.