uncategorized

Looping Code Smell?

I read somewhere in the last few days that someone considered that looping over enumerable lists using a for loop should be considered a code smell.  They went on to say that the preferred way to loop should be using the foreach syntax. 

The reasoning behind the the preference was that the for loop syntax opens the possibility for boundary errors.  Everyone has written a loop over an array where we start at 0 and end at array.Length instead of array.Length - 1.

In the past I would not have cared if a developer had used either method of looping.  Today I opened up some code and the first thing that I noticed was that the it used the for syntax and my immediate reaction was to verify the boundary values in the syntax.  So why should I have to do that?  If we’re going to write a loop that navigates over an entire collection of data, should we really have to worry about coding the boundaries?  We have the foreach syntax which automatically takes care of the boundaries.  Why not use that?

In the modern development world we go to great lengths to abstract away complexity.  I’ve come around to believing that the for syntax doesn’t achieve this.  Sometimes it may be needed, but for looping over entire collections I think it should be avoided.