Name Iterators Based on What They Point To [VD3]
Tip VD3
Loop “iterator objects” are closely associated with the underlying objects they point to, so they’re best named based on what they point to.
Some programming languages have an explicit concept of “iterators,” which lie somewhere between the level of a “numeric index” and “object itself” in terms of the level of abstraction.
Such iterator objects typically behave similar to pointers - essentially just a slight level of indirection to access the underlying object. In most cases, you want to name them similarly to pointers (potentially without something like a p prefix if that convention is part of your coding standards), letting the problem domain type of object be evident in the name itself.
So rather than this:
for (
auto employee_iterator = employees.cbegin();
employee_iterator != employees.cend();
++employee_iterator)
{
std::cout << employee_iterator->Name << std::endl;
}Prefer naming such iterators like this:
for (
auto employee = employees.cbegin();
employee != employees.cend();
++employee)
{
std::cout << employee->Name << std::endl;
}Such names are shorter to read and also make usage code like employee->Name clearer (employee_iterator->Name is more ambiguous or confusing - what is the “name” of an “iterator?”).
The above is assuming that you’re using iterators simply as a means to iterate over and access objects (and other looping constructs like range-based for loops aren’t suitable for your situation).