Naming conventions for Java methods that return boolean

letronje picture letronje · Oct 6, 2010 · Viewed 99.7k times · Source

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?

For e.g. createFreshSnapshot?

Answer

jjnguy picture jjnguy · Oct 6, 2010

The convention is to ask a question in the name.

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?

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

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.

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.

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