I've heard people advise that one should always use the Iterator pattern to control loops rather than throwing an exception (which is how it's done in Python iterators) or using the Sentinel pattern, whereby a special, sentinel value (often null
) is returned to indicate the end of the iteration.
Does best practice advise against the sentinel pattern? If so, why? (other than it not working with the foreach
syntax in Java 1.5).
Edit: Code example 1 - Sentinel Pattern
Reader r = ...;
for( int val = r.read(); val != -1; val = r.read()) {
doSomethingWith(val);
}
Code example 2 - Iterator Pattern
for(Iterator<Thing> it = getAnIterator() ; it.hasNext(); ) {
Thing t = it.next();
doSomethingWith(t);
}