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?
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.
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#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With