返回布尔值的Java方法的命名约定 [英] Naming conventions for Java methods that return boolean

查看:85
本文介绍了返回布尔值的Java方法的命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在其他语言的方法/函数名称末尾使用问号.Java不允许我这样做.作为一种解决方法,我还能如何用Java命名布尔返回方法?在某些情况下,使用方法前面的 is has 应该可以听起来还可以.是否有更好的方法来命名此类方法?

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?

例如createFreshSnapshot?

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.

如果您执行在Java API中针对 isEmpty()的Google搜索,您会得到很多结果.

If you do a Google Search for isEmpty() in the Java API, you get lots of results.

这篇关于返回布尔值的Java方法的命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆