Java – Naming boolean field that is a verb

javanaming

In Java, by convention getter and setter for boolean fields will be isField() and setField(). This works perfectly fine with field names that are adjectives like active, visible, closed, etc.

But how do I name a field that has meaning of a verb, like haveChildren? Add “_ing” to the verb (havingChildren), maybe?

To clarify, I don't have control of the method names (getter and setter) as they are auto-generated by the IDE. So what I need is an appropriate field name so that when the IDE generate a getter for it, it make senses. For example, hasChildren is a perfect field name, but when the IDE generate the getter for the field it would be isHasChildren. How do I solve this?

Best Answer

Short answer:

  • method names aren't supossed to reflect internal implementation but expected behavior.

Long answer:

haveChildren() should be named hasChildren().

Also I don't see hasChildren() as necessarily being the getter for a boolean class member. I guess such a method would find out whether or not a member of type Collection is empty.

Default name an IDE gives to generated getters and setters aren't supossed to be a law set in stone.

Another point: Interfaces have names for yet-to-be-implemented methods.

If method names were supossed to reflect internal implementation, how would someone be able to ever design an interface ? Interfaces don't have an implementation nor they know beforehand what the implementators will do under the hood.

Take for example the Iterator interface in Java.

When you implement Iterator, even when you have a boolean member named next, you are not supossed to rename hasNext() to isNext() or isHavingNext(). That's an implementation detail. In fact, I've implemented Iterator and what I do is have a member of the type of whathever my class has a list of, named next (not a boolean). hasNext() then returns next!=null.

Also, see this:

class patient {
      private boolean hasPulse;
      private boolean isBreathing:
      public boolean isDead(){ return (!hasPulse & !isBreathing);}
}

Note that isDead() is no normal getter.

Take IDEs' productivity tools for what they are.

Related Topic