Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach(... in ...) or .ForEach(); that is the question [duplicate]

Possible Duplicate:
C# foreach vs functional each

This is a question about coding for readability.

I have an XDocument and a List<string> of the names of the elements that contain sensitive information that I need to mask (replace with underscores in this example).

XDocument xDoc;
List<string> propertiesToMask;

This can be written in two ways, using traditional foreach loops, or using .ForEach methods with lamba syntax.

foreach (string propertyToMask in propertiesToMask)
{
    foreach (XElement element in xDoc.Descendants(propertyToMask))
    {
        element.SetValue(new string('_', element.Value.Length));
    }
}

or

propertiesToMask
    .ForEach(propertyToMask => xDoc.Descendants(propertyToMask).ToList()
        .ForEach(element => element.SetValue(new string('_', element.Value.Length))));

Which approach do you think is the most readable, and why? If you prefer the second example, how would you present it for maximum readability?

like image 650
Richard Ev Avatar asked Feb 09 '10 16:02

Richard Ev


2 Answers

foreach (string propertyToMask in propertiesToMask)
{
    foreach (XElement element in xDoc.Descendants(propertyToMask))
    {
        element.SetValue(new string('_', element.Value.Length));
    }
}

Because the spacing makes it very simple to scan. The second is far to cluttered and I have to actually read it.

like image 100
corymathews Avatar answered Nov 15 '22 15:11

corymathews


Eric Lippert has a good entry about this on his blog. To summarize, the very task done by ForEach is to produce side effects which may not be a desirable thing to do with the functional style of programming in C#.

like image 14
mmx Avatar answered Nov 15 '22 15:11

mmx