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:
Long answer:
haveChildren()
should be namedhasChildren()
.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 typeCollection
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 namednext
, you are not supossed to renamehasNext()
toisNext()
orisHavingNext()
. That's an implementation detail. In fact, I've implementedIterator
and what I do is have a member of the type of whathever my class has a list of, namednext
(not a boolean).hasNext()
then returnsnext!=null
.Also, see this:
Note that
isDead()
is no normal getter.Take IDEs' productivity tools for what they are.