Code with style: “get” means Getter

Properties are always accessed via method calls on their owning object. For readable properties there will be a getter method to read the property value. For writable properties there will be a setter method to allow the property value to be updated.

Java BeansSpec  (08.08.1997)

These three sentences have done something weired to my brain. The somehow completely rewired my brain to believe that every method that starts with get means Getter. And this comes with a price: I usually expect a getter to be an O(1) operation. I expect it to be the same three bytecode sequence that is a simple field access and a return. Nothing more. The same goes for a method that starts with set. I don’t expect them to throw exceptions, I don’t expect them to talk to the filesystem or to the network. Just a simple field access, nothing more.

And I am not alone.

Most of the Java programmers are somehow hardwired to have this JavaBean asumption. So naming a method that does more than a simple get or a simple set to an object field should not be named get or set.  If it creates something name it “create”, if it finds something name it “find”, if it stores something name it “store”. You get the idea. As I’m always on the reading side of code, I believe that the these naming conventions are quite good, but they are not only a convention on how to name something, but also a convetion on how to not name things. So if it is not a getter, do not name it get! When looking for alternatives,  Stephen Colebourne did a nice collection on common prefixes in the Java world.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s