I heard that people are advised to always use the iterator pattern to control the loops instead of throwing an exception (as it is made in Python Iterators ) or using the Sentinel pattern , which returns a special, sentinel value (often null) indicating the end of the iteration.
Does best practice recommend against sentinel pattern? If so, why? (except that it does not work with syntax foreachin Java 1.5).
Edit: Code Example 1 - Sentinel Template
Reader r = ...;
for( int val = r.read(); val != -1; val = r.read()) {
doSomethingWith(val);
}
Code Sample 2 - Iterator Pattern
for(Iterator<Thing> it = getAnIterator() ; it.hasNext(); ) {
Thing t = it.next();
doSomethingWith(t);
}
source
share