Saturday, September 20, 2008

How verbose is too verbose?

A common thing to do in code is to perform an action on each element in an array of objects. In C# there are two main ways to write this:
// Lets just assume this list of strings has been populated with lots of strings
List<string> allStrings = GetLotsOfStrings ();

// Method 1: The for loop
for (int i = 0; i < allStrings.Count; i++)
DoStuff (allStrings[i]);

// Method 2: The foreach loop
foreach (string s in allStrings)
DoStuff (s);
However, both of those methods are far too verbose. There is another way, which is much much nicer!
allStrings.ForEach(DoStuff);
How awesome is that, eh?

5 comments:

Anonymous said...

The downside to that is it only works with List<T>. Arrays would require:

Array.ForEach(allStrings, DoStuff);

So use Mono.Rocks, in particular rocks-playground:

http://anonsvn.mono-project.com/viewvc/branches/rocks-playground/?revision=HEAD

Then you can do the following for List<T>, arrays, and any other IEnumerable<T> type:

allStrings.Apply(DoStuff).Apply();

Alan said...

But if you happen to be constrained to .NET 2.0, you're stuck with using List<T> .ForEach (Action<T>) and Array.Method<T>(T[], Action<T>);

One rock (which may already exist) that i'd love to use would be:

IEnumerable<T>.ForEach(Predicate<T>, Action<T>);

Implemented as:
foreach (T t in enumerable)
if (predicate(t))
action(t);

RichB said...

Your code would be much nicer if you took an alternative approach - raise the level of abstraction by creating a concrete class deriving from List<string>. GetLotsOfStrings() would return an instance of this new class. Then the DoStuff() method would become a method on the new class and do the iteration over all strings.

It's a refactoring which makes all your code better.

Alan said...

In that case you may as well argue that you should never have to use a foreach loop in the main logic of your application. You should create a class and execute its "DoWork" method instead ;)

RichB said...

Yes.

(or at least it's a code smell)

Hit Counter