返回布尔值的 Java 方法的命名约定 [英] Naming conventions for Java methods that return boolean
问题描述
我喜欢在其他语言的方法/函数名称末尾使用问号.Java 不允许我这样做.作为一种解决方法,我还能如何在 Java 中命名布尔返回方法?在某些情况下,在方法前面使用 is
、has
、should
、can
听起来没问题.有没有更好的方法来命名这些方法?
I like using question mark at the end of method/function names in other languages. Java doesn't let me do this. As a workaround how else can I name boolean returning methods in Java? Using an is
, has
, should
, can
in the front of a method sound okay for some cases. Is there a better way to name such methods?
例如创建FreshSnapshot?
For e.g. createFreshSnapshot?
推荐答案
约定是在名称中提出问题.
The convention is to ask a question in the name.
以下是一些可以在 JDK 中找到的示例:
Here are a few examples that can be found in the JDK:
isEmpty()
hasChildren()
这样,名字的读起来就像末尾有问号一样.
That way, the names are read like they would have a question mark on the end.
集合是否为空?
这个节点有孩子吗?
Is the Collection empty?
Does this Node have children?
然后,true
表示是,false
表示否.
And, then, true
means yes, and false
means no.
或者,您可以像断言一样阅读它:
Or, you could read it like an assertion:
集合是空的.
该节点有子节点
The Collection is empty.
The node has children
注意:
有时您可能想将方法命名为类似 createFreshSnapshot?
的名称.没有问号,这个名字意味着该方法应该创建一个快照,而不是检查是否需要.
Note:
Sometimes you may want to name a method something like createFreshSnapshot?
. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.
在这种情况下,您应该重新考虑您实际询问的内容.像 isSnapshotExpired
这样的名称是一个更好的名称,它传达了该方法在被调用时会告诉您的信息.遵循这样的模式还有助于让您的更多函数保持纯净且没有副作用.
In this case you should rethink what you are actually asking. Something like isSnapshotExpired
is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.
如果您执行 Google 搜索isEmpty()
,你会得到很多结果.
If you do a Google Search for isEmpty()
in the Java API, you get lots of results.
这篇关于返回布尔值的 Java 方法的命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!