Disclaimer
There is a better way to iterate over collections in Objective-C 1.0. You really should use it. It’s easier to write, easier to read, less prone to bugs, faster, and makes what I’m going to rant about here a non-issue, because you won’t have any NSEnumerator
variables in your code.
Badly Named Problem
The standard iteration idiom in Objective-C 1.0 is:
NSEnumerator *enumerator = [collection objectEnumerator];
id element = nil;
while( nil != (element = [enumerator nextObject]) ) {
;//do stuff...
}
Unfortunately, I see otherwise steller programmers name their NSEnumerator
variables “enumerator”. That’s always wrong, because it does not tell you what the enumerator enumerates. We already know that enumerator
enumerates things, because it’s type is NSEnumerator
, unless it’s name tells us more then that it’s hardly better then no name at all.
This is an especially amateurish practice because …
Naming an Enumerator Well is Easy!
Call it, the plural of the element
variable. And if that won’t work you can always fall back on calling it collectionEnumerator
.
For example, to fix:
NSEnumerator *enumerator = [input objectEnumerator]; NSString *path = nil; while (path = [enumerator nextObject])
We should name enumerator
paths
or inputEnumerator
. You might find “paths” to be too close to “path” in which case let the “plural form” of element
be everyElement
, giving everyPath
.
These rules can be applied without much thought, but will improve the clarity of code.
Why enumerator
is Worse Than i
Firstly, the practice of naming an the index in a for
-loop i
is not good. You can avoid it by renaming i
to thingThatIsIndexedIndex
.
But at least, for(int i = 0; i < collection.size(); i++)
, is concise; therefore better than a equally-poorly-named NSEnumerator
.
Also, there is something to be said for the idiom you can just use collection[i]
over declaring an extra element
variable.
The Right Choice
Everyone agrees informative names are good, yet poorly named enumerators are everywhere (just browse Apple’s sample code!) Poorly named enumerators persist because nobody really uses an enumerator per se, they are just part of an iteration idiom. (So stop declaring them and iterate smarter). When was the last time you saw code that did anything with an enumerator
besides [enumerator nextObject]
in a while
loop?
But bad habits matter. Don’t pick up the habit of naming something poorly when it’s easy to do the right thing.