Some patterns are more obvious than others. This is one of the more obvious patterns, but it’s violated often enough to deserve enunciation.
Just about every program out there uses an iterator for one reason or another. Without them, we can’t build for loops, and more than a few while loops require iterators as well.
They let us perform simple operations on buffers and arrays.
They let us control flow of information.
Fundamentally, an iterator is a control line. It is essential that we maintain the integrity of our controls, because without that control we exponentially increase the complexity of the problem.
Iterator Abuse is the act of violating the integrity of an iterator, which destroys the line of control and makes the program act in complicated or unexpected ways. This abuse is performed in a number of ways:
- Reusing the iterator before its control function has been completed
- Modifying the iterator inside of the loop (usually by a non-standardized unit)
- Passing the iterator into a function without protection
- Using your only copy of a pointer as an iterator
What can you do?
Iterator abuse is one of the more easily preventable issues in our programs. We have to adhere to a few simple rules:
- Only use specially-marked values as iterators (the classic name is “i” or “j”)
- Only use iterators for iteration
- Iterate each value only ONCE per cycle (no i++; i+=j)
- In cases where we want to modify the iterator by a non-standardized unit (for example, by a number of bits equivalent to a structure), use extreme caution
- If iterating inside of a for loop, never modify the iterator
- If iterating over a pointer, iterate over a copy of that pointer instead of the original
- Either avoid non-standard loop termination (break, etc.) or avoid referencing the iterator outside of the loop
- Don’t pass iterators into functions which might change the iterator value