为什么在 Java 方法名称中使用数字是错误的?
不久前,我记得有人告诉我不要在 Java 方法名称中使用数字。最近,我有一位同事问我为什么,但我怎么也想不起来。
根据 Sun(现在是 Oracle)的说法,方法名称的一般命名约定是:
方法应该是动词,大小写混合 第一个字母小写,与 每个内部单词的第一个字母 大写。
这并没有具体说明数字可以不被使用,尽管通过省略你可以看到不建议这样做。
考虑一下您想要根据特定年份执行某些逻辑的情况(我的同事遇到的情况),例如,2011 年生效的新政策,因此您的应用程序必须根据信息采取行动并根据年份进行处理。常识可以告诉您可以调用该方法:
boolean isSessionPost2011(int id) {}
在方法名称中使用数字是否可以接受(尽管标准的措辞如何)?如果没有,为什么?
编辑:“这并没有明确表示不能使用数字,尽管通过遗漏您可以看到不建议这样做。”也许我的措辞不正确。标准规定“方法应该是动词”。我读到这个是说考虑到数字不是动词,那么方法名称不应该使用数字。
Sometime ago, I remember being told not to use numbers in Java method names. Recently, I had a colleague ask me why and, for the life of me, I could not remember.
According to Sun (and now Oracle) the general naming convention for method names is:
Methods should be verbs, in mixed case
with the first letter lowercase, with
the first letter of each internal word
capitalized.
This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised.
Consider the situatiuon (that my colleague has) where you want to perform some logic based on a specific year, for instance, a new policy that takes affect in 2011, and so your application must act on the information and process it based on it's year. Common sense could tell you that you could call the method:
boolean isSessionPost2011(int id) {}
Is it acceptable to use numbers in method names (despite the wording of the standard)? If not, why?
Edit: "This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised." Perhaps I worded this incorrectly. The standard says 'Methods should be verbs'. I read this to say that considering a number is not a verb, then method names should not use numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
标准 Java 类库充满了带有数字的类和方法,例如
Graphics2D
。The standard Java class library is full of classes and methods with numbers in it, like
Graphics2D
.该方法似乎......过于具体。
你不能改用:
吗?
这样,下次您将策略应用于特定日期之后的任何内容时,您无需复制粘贴旧方法并更改号码 - 您只需使用不同的日期调用它即可。
The method seems ... overly specific.
Couldn't you instead use:
?
That way the next time you have a policy applied to anything after a particular date, you don't need to copy-paste the old method and change the number - you just call it with a different date.
当然,在方法名称中使用数字是可以接受的。但根据你的例子,这就是为什么它通常不受欢迎的原因。假设现在有 2012 年的新政策。现在有 2014 年的新政策。也许还有 2020 年!因此,您有四种大致等效的方法。
您想要的不是布尔值,而是根据是否找到策略来执行某些操作或不执行任何操作的策略。因此,方法 void processPolicy(Structure yourStructure);将是一种更好的方法 - 现在您可以屏蔽您正在根据年份进行查找,并且不必每年都有单独的方法,甚至将其限制为每年只有一个策略(也许会发生一项策略)例如,在两个不同的年份,或仅三个月)。
Sure, it's acceptable to use numbers in method names. But as per your example, that's why it's generally frowned upon. Let's say that there is now a new policy in place for the year 2012. Now, there's a new policy in place for 2014. And maybe 2020! So, you have four methods that are roughly equivalent.
What you want isn't a boolean but rather a strategy to do something, or do nothing, based on whether or not a policy was found. Hence, a method void processPolicy(Structure yourStructure); would be a better approach - now you can shield that you're doing a lookup based on the year, and don't have to have separate methods per year, or even limit it to just one policy per year (maybe a policy takes place in two different years, for example, or just three months).
Java 语言规范 似乎关于此主题相当具体:
The Java Language Specification seems fairly specific on this topic:
我当然不会那样阅读 Java 风格指南。从 Java 类库中的大量示例来看,它们也不是。
我想唯一需要注意的是 JSG 建议使用有意义的名称。推论是,只有当数字在语义上有意义时,才应该在标识符中使用数字。很好的例子有
甚至“int2Real”也具有民间意义。
更新
@biziclomp 提出了
LayoutManager2
的情况,并声称2
没有传达任何含义。以下是 javadoc 关于此接口的用途的说明:
由此看来,我认为名称中的
2
是有意义的。基本上,它是说您可以将其视为LayoutManager
的继承者。我想这可以用语言来表达,但是请参阅上面的示例,了解如何使用数字作为简写。@BlueRaja 写道:
风格指南的建议并不是名称应该解释事物。相反,它建议它们应该是有意义的。 (有关解释,请参阅 javadoc。)显然,意义是相对的,但在标识符变得难以阅读和难以键入之前,可以放入标识符中的信息量存在实际限制。
我的看法是,标识符应该提醒读者所命名的事物(类、字段、方法等)的含义。
这是一种权衡。
I certainly wouldn't read the Java Style Guide that way. And judging from numerous examples in the Java class libraries, neither do they.
I guess the only caveat is that the JSG recommends use of meaningful names. And the corollary is that you should only use numbers in identifiers when they are semantically meaningful. Good examples are
Even "int2Real" is meaningful in a folksy way.
UPDATE
@biziclomp has raised the case of
LayoutManager2
, and claims that the2
conveys no meaning.Here's what the javadoc says about the purpose of this interface:
From this, I would say that the
2
in the name is meaningful. Basically, it is saying that you can view this as a successor toLayoutManager
. I guess that could have been said in words, but see the examples above on how numbers where numbers are used as short-hand.@ BlueRaja writes:
The advice of the Style Guide is NOT that names should explain things. Rather, it advises that they should be meaningful. (For the explanation, refer to the javadoc.) Obviously meaningfulness is relative, but there is a practical limit on the amount of information you can put into an identifier before it becomes hard to read and hard to type.
My take is that the identifier should remind the reader what the meaning of the thing (class, field, method, etc) that is named.
It is a trade-off.
仅此措辞就已经表明他们使用了比通常更通用的动词含义,其中只有
is
是动词,session
和session
都不是动词。post
是动词。该句子的含义类似于方法名称应该是动词或动词短语,...,并且数字很可能是动词短语的一部分。这个想法是,一个完整的方法调用可以被理解为一个完整的句子,主语是点之前的宾语,动词是方法名称,附加对象是方法的参数:
(大多数此类句子要么是疑问句,要么是祈使句。)
您的方法名称(从命名约定的角度来看)唯一的问题是句子的主语(会话)不是该对象的
this
对象。你的方法,而是一个参数,但我认为这对于Java是无法避免的(请有人证明我错了)。对于多参数方法,smalltalk 方法会更好:(
其中
replace:with:
是 string 类的一种方法。)This phrasing alone already shows that they use a more general meaning of verb than the usual, where only
is
would be the verb, neithersession
norpost
are verbs. The sentence means something like Method names should be verbs or verbal phrases, ..., and numbers can very well be parts of verbal phrases.The idea is that a complete method call can be read as a complete sentence, with the subject being the object before the dot, the verb being the method name, and additional objects being the arguments to the method:
(Most such sentences would be either questioning or imperative ones.)
Your method name has (from a naming convention viewpoint) the only problem that the subject of the sentence (the session) is not the
this
object of your method, but an parameter, but this can't be avoided with Java, I think (please someone prove me wrong).For multiple-parameter methods the smalltalk approach would work better:
(where
replace:with:
is one method of the string class.)是的,在某些情况下。例如,也许您想要处理 X.509 证书。我认为编写一个名为
handleX509Certificate
的方法是完全可以接受的。Yes, in some circumstances. For example, maybe you want to handle X.509 certificates. I think it would be perfectly acceptable to write a method called
handleX509Certificate
.我认为在方法名称中使用数字的唯一问题是,它可能表明您的设计中的某些内容可以改进。 (我犹豫是否要说“是错误的”。)例如,在你的例子中,你说你有一个在2011年之后生效的具体政策。然而,有一个专门检查那一年的方法似乎过于具体和神奇——数字-y。相反,我建议创建一个通用函数来检查事件是否在 Anon 建议的指定日期之后发生。
(Anon 的答案是在我的答案写到一半时突然出现的,所以如果我看起来只是在重复他所说的话,我很抱歉。我觉得我的答案扩展了他所说的内容,所以我想无论如何我都会发布它.)
The only problem I see with using numbers in method names is that it may be an indication that something in your design could be improved upon. (I hesitate to say "is wrong.") For instance, in your example, you stated that you have a specific policy which comes into effect after 2011. However, having a method specifically to check for that year seems overly specific and magic-number-y. I'd instead suggest creating a generalized function to check if an event occurred after a specified date as Anon suggested.
(Anon's answer popped up while I was halfway through mine, so my apologies if it seems like I'm just duplicating what he said. I felt that mine expanded on what he was saying a bit, so I thought I'd post it anyway.)
我会考虑将你的方法称为其他名称。确切地说,没有什么与数字相悖的,但如果项目推迟了发布日期会发生什么?您将有一个名为 post2011 的方法 - 现在它应该被称为 post2012。考虑将其称为 postProjNameImplentation 吧?
I would consider calling your method something else. Nothing against numbers exactly, but what happens if the project slips it release date? You'll have a method called post2011 - when it should be called post2012 now. Consider calling it postProjNameImplentation instead maybe?
数字的使用本身并不错,但通常它们不是很常见。
在具体情况下,我认为
isSessionPost2011(int id) {}
不是一个好名字。但更好的是isSessionPostYear(int id, intyear) {}
更具可扩展性以供将来使用。The use of number it is not bad itself, but usually they are not very common.
in the specific case, I don't think
isSessionPost2011(int id) {}
is a good name. but it is betterisSessionPostYear(int id, int year) {}
more extensible for future uses.事实上,它是一种编码约定,并且动词“应该”的使用表明您允许在方法名称中使用数字,但建议不要使用数字。但是在您的示例中,为什么不将相同的代码概括为?
The fact it is a coding convention and the use of the verb "should" suggest you that digits are permitted but advised against in methods names. However in your example, why not generalizing the same code as?
我们一直在使用它们,就像您展示的示例一样。也适用于接口版本,例如
IConnection2
和IConnection3
。Eclipse 也没有抱怨它是一个非传统的名称。 :)
但是可以接受吗?这取决于你。
We use 'em all the time, like the example you showed. Also for interface versions, like
IConnection2
andIConnection3
.Eclipse doesn't complain that it's a nontraditional name, either. :)
But acceptable? That's kind-of up to you.
永远不要忘记——规则是用来打破的。唯一绝对的应该是没有绝对。
Don't ever forget - rules are made to be broken. The only absolute should be that there are no absolutes.
我不认为有一个本身的理由来避免在标识符中使用数字,尽管在您描述的情况下,我不知道我会使用它。相反,我会将该方法命名为
boolean isPolicyXyzApplicable(int id)
。如果这是一项预计会随着时间的推移而发生更多变化的策略,请考虑将策略分为不同的类,这样您就不会最终长出一长串
if(isPolicyX) ... else if(isPolicyY) ... else if(isPolicyZ) ...
在您的方法中。一旦将其分解出来,请使用抽象或接口方法Policy.isApplicableTo(transaction)
和Policy
对象集合来确定要做什么。I don't believe there's a per se reason to avoid numbers in identifiers, although in the case you describe, I don't know that I'd use it. Rather, I'd name the method something like
boolean isPolicyXyzApplicable(int id)
.If this is a policy that's expected to change more over time, consider splitting policies out into different classes so you don't end up growing a long vine of
if(isPolicyX) ... else if(isPolicyY) ... else if(isPolicyZ) ...
in your methods. Once this is factored out, use an abstract or interface methodPolicy.isApplicableTo(transaction)
and a collection ofPolicy
objects to determine what to do.只要你有使用数字的理由,那么我认为就可以了。
对于您的示例,可能有 2 个 isSessionPost 方法,那么您将如何命名它们? isSessionPost 和 isSessionPost2?说实话不太清楚。
请记住,所有名称都必须有意义,这样就不会出错。
As long as you have a reason for using numbers, then imho I think it's fine.
For your example, there might be 2 isSessionPost method, so how would you name them? isSessionPost and isSessionPost2? Not very clear to be honest.
Just remember that all names must be meaningful and you won't go wrong.
我认为在您的情况下,可以将其用作一次性标记,特别是如果您预计该方法只会存在很短的一段时间并最终被弃用。
如果我理解您的用例,您需要将一些遗留数据引入新版本的应用程序中。如果是这种情况,那么一定要添加此方法,将其标记为@deprecated,并在所有客户端更新后停用它。
另一方面拉尔夫在这里 有一个有效的观点。不要让这个项目溜进 2012 年:)
I think in your case it's OK to use it as a one-off marker, specifically if you expect that the method will only live for a short period of time and eventually be deprecated.
If I understand your use case, you need to bring in some legacy data into the new version of your application. If this is the case, then definitely add this method, mark it
@deprecated
and retire it when all your clients are updated.On the other hand Ralph here has a valid point. Don't let this project to slip into 2012 :)
没什么问题
哇!该网站不喜欢这些方法名称!我得到了验证码!
nothing is wrong
wow! this website doesn't like these method names! I got captchaed!