Patterns: Protect the Iterators!

Some patterns are more obvious than others. This is one of the more obvious patterns, but it’s violated often enough to deserve enunciation.

Iterator Abuse

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
  • etc.

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:

  1. Only use specially-marked values as iterators (the classic name is “i” or “j”)
  2. Only use iterators for iteration
  3. Iterate each value only ONCE per cycle (no i++; i+=j)
  4. 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
  5. If iterating inside of a for loop, never modify the iterator
  6. If iterating over a pointer, iterate over a copy of that pointer instead of the original
  7. Either avoid non-standard loop termination (break, etc.) or avoid referencing the iterator outside of the loop
  8. Don’t pass iterators into functions which might change the iterator value

Lesson: Iterators are oft-abused values. Remember that their purpose is to establish simple loops, and don’t go crazy with them.

Facebook Auto Publish Powered By :