问题
What is the right way to name a variable
int numItems;
vs.
int itemCount;
or constant:
public static final int MAX_NUM_ITEMS = 64;
vs.
public static final int MAX_ITEM_COUNT = 64;
回答1:
In "Code Complete," Steve McConnell notes that "Number" is ambiguous. It could be a count, or an index, or some other number.
"But, because using Number so often creates confusion, it's probably best to sidestep the whole issue by using Count to refer to a total number of sales and Index to refer to a specific sale."
回答2:
item_count or itemCount (there's a religious war brewing there, though)
回答3:
For Java I would use itemCount
and MAX_ITEM_COUNT
. For Ruby, item_count
and MAX_ITEM_COUNT
. I tend not to use names that can be interpreted wrongly (numItems
may be a shortcut for numerate_items
or number_of_items
), hence my choice. Whatever you decide, use it constantly.
回答4:
It's a matter of personal preference, just make sure you are consistent throughout your code. If you're working with others check what's been done in existing code.
For the constant I would find MAX_ITEMS
more logical than MAX_NUM_ITEMS
or similar, it just sounds better to me.
来源:https://stackoverflow.com/questions/6358588/how-to-name-a-variable-numitems-or-itemcount