Naming conventions for java methods that return boolean(No question mark)

前端 未结 7 910
深忆病人
深忆病人 2020-12-02 10:49

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 method

7条回答
  •  星月不相逢
    2020-12-02 11:24

    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.

提交回复
热议问题