如何命名变量:numItems 或 itemCount?
常量的正确方法是什么
int numItems;
命名变量与
int itemCount;
:
public static final int MAX_NUM_ITEMS = 64;
与
public static final int MAX_ITEM_COUNT = 64;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在“代码完整”中,史蒂夫·麦康奈尔指出“数字”是不明确的。它可以是计数、索引或其他数字。
In "Code Complete," Steve McConnell notes that "Number" is ambiguous. It could be a count, or an index, or some other number.
item_count 或 itemCount (不过那里正在酝酿一场宗教战争)
item_count or itemCount (there's a religious war brewing there, though)
对于 Java,我将使用
itemCount
和MAX_ITEM_COUNT
。对于 Ruby,为item_count
和MAX_ITEM_COUNT
。我倾向于不使用可能被错误解释的名称(numItems
可能是numerate_items
或number_of_items
的快捷方式),因此我的选择。无论你决定什么,都要不断地使用它。For Java I would use
itemCount
andMAX_ITEM_COUNT
. For Ruby,item_count
andMAX_ITEM_COUNT
. I tend not to use names that can be interpreted wrongly (numItems
may be a shortcut fornumerate_items
ornumber_of_items
), hence my choice. Whatever you decide, use it constantly.这是个人喜好的问题,只需确保整个代码保持一致即可。如果您正在与其他人合作,请检查现有代码中做了什么。
对于常量,我会发现
MAX_ITEMS
比MAX_NUM_ITEMS
或类似的更符合逻辑,它对我来说听起来更好。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 thanMAX_NUM_ITEMS
or similar, it just sounds better to me.这实际上取决于你。两种类型的命名约定是
驼峰式命名法和蛇形命名法
从命名中可以看出,驼峰式命名法在变量的开头部分有一个小写字母,后跟大写单词,
例如 itemCount。
Snake case 是一个连续的单词,单词之间有一个下划线“_”
例如item_count
就命名而言,numItems 对于其他人来说读起来相当混乱。但 itemCount 是一个计数器变量的好名字
It actually depends on you. The two types of naming conventions are
camelCase and snake_case
As you can identify from the naming, camel case has one small letter in the initial part of the variable followed by the Capital words
Eg itemCount.
snake case is a continuous word with an underscore ' _ ' in between the words
Eg item_count
As far as the naming is concerned, numItems is quite confusing for others to read. But itemCount is a good name for a counter variable
我也一直想知道这个问题,并且认为在所有这些答案中都很有趣,没有人只说
items
,但我可以看到,如果它在包含以下内容的代码库中,这可能是一个坏名字对象或数组,但也许可以像 SQL 中的字段名称一样。但我刚刚意识到使用像
numItems
这样的东西的一个缺点是,如果您有多个相似的字段并使用具有智能感知或自动完成功能的任何内容,则存在意外使用错误字段的风险,而item_count
从您正在计算的事物开始。I've been wondering about this question too, and thought it interesting in all these answers that no one said just
items
, but I can see that would be a bad name perhaps if it's in a codebase that has objects or arrays, but maybe okay as like a field name in SQL.But one downside I just realized to going with something like
numItems
is that if you have multiple similar fields and use anything with intellisense or autocomplete, there's a risk of accidentally using the wrong field, whereasitem_count
begins with the thing you're counting.