《The Art of Readable Code》的笔记-第12页
- 章节名：Packing Information into Names
- 页码：第12页 2013-02-05 12:12:44
Names like i, j, iter, and it are commonly used as indices and loop iterators. Even though these names are generic, they’re understood to mean “I am an iterator.” (In fact, if you used one of these names for some other purpose, it would be confusing—so don’t do that!) But sometimes there are better iterator names than i, j, and k. For instance, the following loops find which users belong to which clubs:for (int i = 0; i < clubs.size(); i++) for (int j = 0; j < clubs[i].members.size(); j++) for (int k = 0; k < users.size(); k++) if (clubs[i].members[k] == users[j]) cout << "user[" << j << "] is in club[" << i << "]" << endl;In the if statement, members and users are using the wrong index. Bugs like these are hard to spot because that line of code seems fine in isolation:if (clubs[i].members[k] == users[j])In this case, using more precise names may have helped. Instead of naming the loop indexes (i,j,k), another choice would be (club_i, members_i, users_i) or, more succinctly (ci, mi, ui). This approach would help the bug stand out more:if (clubs[ci].members[ui] == users[mi]) # Bug! First letters don't match up.When used correctly, the first letter of the index would match the first letter of the array:if (clubs[ci].members[mi] == users[ui]) # OK. First letters match.
说明 · · · · · ·