为什么在 Java 方法名称中使用数字是错误的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4964628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:49:00  来源:igfitidea点击:

Why is it wrong to use numbers in Java method names?

javamethodsstandards

提问by Cyntech

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.

前段时间,我记得有人告诉我不要在 Java 方法名称中使用数字。最近,我有一个同事问我为什么,对于我的生活,我想不起来了。

According to Sun (and now Oracle) the general naming convention for method names is:

根据 Sun(以及现在的 Oracle)的说法,方法名称的一般命名约定是:

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

方法应该是动词,大小写混合,首字母小写,每个内部单词的首字母大写。

Code Conventions of Java

Java的代码约定

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:

考虑一下您希望基于特定年份执行某些逻辑的情况(我的同事遇到的情况),例如,一项在 2011 年生效的新政策,因此您的应用程序必须根据信息采取行动并根据年份对其进行处理. 常识可以告诉您,您可以调用该方法:

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.

编辑:“这并没有特别说明不能使用数字,尽管您可以看到不建议使用它。” 也许我措辞不正确。标准说“方法应该是动词”。我读这个是为了说考虑到数字不是动词,那么方法名称不应该使用数字。

回答by EboMike

The standard Java class library is full of classes and methods with numbers in it, like Graphics2D.

标准 Java 类库中充满了带有数字的类和方法,例如Graphics2D.

回答by Anon.

The method seems ... overly specific.

该方法似乎......过于具体。

Couldn't you instead use:

你不能改用:

boolean isSessionAfter(int id, Date date)

?

?

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.

这样,下次在特定日期之后将策略应用于任何内容时,您无需复制粘贴旧方法并更改数字 - 您只需使用不同的日期调用它。

回答by MetroidFan2002

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.

当然,在方法名称中使用数字是可以接受的。但根据你的例子,这就是为什么它通常不受欢迎的原因。假设现在有一项针对 2012 年的新政策。现在,有一项针对 2014 年的新政策。也许是 2020 年!因此,您有四种大致等效的方法。

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).

您想要的不是布尔值,而是根据是否找到策略来做某事或什么都不做的策略。因此,有一个方法 void processPolicy(Structure yourStructure); 将是一种更好的方法 - 现在您可以屏蔽您正在根据年份进行查找,并且不必每年使用单独的方法,甚至将其限制为每年只有一个政策(可能会发生政策)例如,在两个不同的年份,或仅仅三个月)。

回答by Greg Hewgill

The Java Language Specificationseems fairly specificon this topic:

Java语言规范似乎相当具体的关于这一主题:

3.8 Identifiers

An identifieris an unlimited-length sequence of Java lettersand Java digits, the first of which must be a Java letter.

...

The Java letters include uppercase and lowercase ASCII Latin letters A-Z(\u0041-\u005a), and a-z(\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.

The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).

3.8 标识符

一个标识符是无限长序列的Java字母爪哇位,其中第一个必须是一个Java字母。

...

Java 字母包括大写和小写 ASCII 拉丁字母A-Z( \u0041-\u005a) 和a-z( \u0061-\u007a),以及出于历史原因的 ASCII 下划线 ( _, or \u005f) 和美元符号 ( $, or \u0024)。该$字符应仅用于机械生成的源代码,或者很少用于访问遗留系统上预先存在的名称。

“Java 数字”包括 ASCII 数字 0-9 ( \u0030-\u0039)。

回答by Stephen C

This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised.

这并没有特别说明不能使用数字,尽管您可以看到不建议使用它。

I certainly wouldn't read the Java Style Guide that way. And judging from numerous examples in the Java class libraries, neither do they.

我当然不会那样阅读 Java 风格指南。从 Java 类库中的大量示例来看,它们也不是。

I guess the only caveat is that the JSG recommends use of meaningfulnames. And the corollary is that you should only use numbers in identifiers when they are semantically meaningful. Good examples are

我想唯一的警告是 JSG 建议使用有意义的名称。推论是,您应该只在标识符中使用具有语义意义的数字。很好的例子是

  • "3D",
  • "i18n" ( == internationalization ),
  • "2020" (the year),
  • "X509" (a standard), and so on.
  • “3D”,
  • "i18n" ( == 国际化 ),
  • “2020”(年),
  • “X509”(一种标准)等等。

Even "int2Real" is meaningful in a folksy way.

甚至“int2Real”在民间也很有意义。



UPDATE

更新

@biziclomp has raised the case of LayoutManager2, and claims that the 2conveys no meaning.

@biziclomp 提出了 的情况LayoutManager2,并声称2没有任何意义。

Here's what the javadoc says about the purpose of this interface:

下面是 javadoc 关于这个接口的目的的说明:

This minimal extension to LayoutManageris intended for tool providers who wish to the creation of constraint-based layouts. It does not yet provide full, general support for custom constraint-based layout managers.

这个最小的扩展LayoutManager适用于希望创建基于约束的布局的工具提供者。它尚未为基于自定义约束的布局管理器提供全面的、通用的支持。

From this, I would say that the 2in the name ismeaningful. Basically, it is saying that you can view this as a successor to LayoutManager. I guess that could have been said in words, but see the examples above on how numbers where numbers are used as short-hand.

由此,我会说2名字中的有意义的。基本上,它是说您可以将其视为LayoutManager. 我想这可以用文字来表达,但请参阅上面的示例,了解如何将数字用作简写。

@ BlueRaja writes:

@BlueRaja 写道:

The 2 does not explain anything - how is LayoutManager2 any different from LayoutManager?

2 没有解释任何东西 - LayoutManager2 与 LayoutManager 有何不同?

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.

风格指南的建议不是名字应该解释事情。相反,它建议它们应该是有意义的。(有关解释,请参阅 javadoc。)显然意义是相对的,但是在标识符变得难以阅读和难以输入之前,可以放入标识符的信息量是有实际限制的。

My take is that the identifier should remindthe reader what the meaning of the thing (class, field, method, etc) that is named.

我的看法是标识符应该提醒读者被命名的事物(类、字段、方法等)的含义。

It is a trade-off.

这是一种权衡。

回答by Pa?lo Ebermann

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

方法应该是动词,大小写混合,首字母小写,每个内部单词的首字母大写。

This phrasing alone already shows that they use a more general meaning of verbthan the usual, where only iswould be the verb, neither sessionnor postare verbs. The sentence means something like Method names should be verbs or verbal phrases, ..., and numbers can very well be parts of verbal phrases.

仅此短语就已经表明他们使用了比通常更一般的动词含义,其中只有is动词,既不是动词,session也不post是动词。句子的意思是方法名称应该是动词或口头短语,...,并且数字很可能是口头短语的一部分。

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:

这个想法是一个完整的方法调用可以读作一个完整的句子,主语是点之前的宾语,动词是方法名称,附加对象是方法的参数:

if (buffer.isEmpty()) 
    buffer.append(word);

(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 thisobject of your method, but an parameter, but this can't be avoided with Java, I think (please someone prove me wrong).

您的方法名称(从命名约定的角度来看)唯一的问题是句子(会话)的主题不是this您的方法的对象,而是一个参数,但是我认为 Java 无法避免(请有人证明我错了)。

For multiple-parameter methods the smalltalk approach would work better:

对于多参数方法,smalltalk 方法效果更好:

"Hello" replace: "e" with: "x"

(where replace:with:is one method of the string class.)

(其中replace:with:是字符串类的一种方法。)

回答by guido

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?

事实上,它是一种编码约定,动词“应该”的使用表明数字是允许的,但建议不要在方法名称中使用。但是,在您的示例中,为什么不概括与相同的代码?

session.isPostYear(int year);

回答by Ralph

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?

我会考虑将您的方法称为其他方法。与数字无关,但如果项目推迟发布日期会发生什么?您将拥有一个名为 post2011 的方法 - 现在应该将其称为 post2012。可以考虑将其称为 postProjNameImplentation 吗?

回答by Filippo De Luca

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 better isSessionPostYear(int id, int year) {}more extensible for future uses.

在具体情况下,我认为isSessionPost2011(int id) {}不是一个好名字。但isSessionPostYear(int id, int year) {}对于未来的使用,它更好地更具可扩展性。

回答by ide

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.

是的,在某些情况下。例如,您可能想要处理 X.509 证书。我认为编写一个名为handleX509Certificate.