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?

6 comments:

Jonathan Pryor 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)

gaohui said...

Have you noticed ed hardy Clothing that she is spending time with ed hardy sale one person in particular ed hardy and they seemed to come from ed hardy UK nowhere. When you ask how she ed hardy cheap knows them she becomes aloof and ed hardy Clothes disinterested. Is there someone's house ed hardy store she seems to be always going to? This edhardy.com could spell something is wrong with the christian audigier sale relationship. Is she taking trips, possibly day ed hardy dresses trips or small vacations without you? If ed hardy Polos she was doing this before you even ed hardy sandals got married or dated, then it may be okay, but if it is a recent ed hardy Jackets development then you may have problems.

Hit Counter