Monday, December 08, 2008

To Get or To Do

So, the standard for getting property values from a model in Java is to call a getXYZ() method, like getName(), getAge(), getPrice(), etc...

Sometimes though, a model may have a property calculated dynamically, such as total. Other times, a property is determined dynamically based on passed parameters, like sales for a particular customer.

In these cases, do you prefer the name of the method to be getTotal() and getSales(Customer customer) or would names that reflect the behavior be more preferable, like calculateTotal() and determineSalesFor(Customer customer)?

4 comments:

Soleone said...

Me personally would go for getProperty() instead of calculateProperty(), even tough it's not a simple getter. I hate all the different naming schemes of Java methods, and I think in Ruby people handle it pretty similar (at least the projects I know of).

You should note in the javadoc though, that the property is calculated to make that clear.

My 2 cents...

Jean said...

In anything like a web or very dynamic environement/framework, I would use the getProperty naming scheme, if only to be on the safe side of BeanUtils

holger said...

I know that this is impossible to understand for many people, but calling methods "getFoo()" is actually completely backwards and wrong because *the acting object doesn't get anything*. Sad but true - the JavaBeans property naming conventions were written by someone who didn't really understand OO; it's a purely procedural view onto data, and that is the reason why you struggle to properly name dynamic object behaviour.
Other languages (Smalltalk, Objective-C) have similar conventions without the "get" and it works fine. FWIW the JDK itself is inconsistent in this regard as well; take a look at some of the NIO methods.
That being said, the mindless adherence to convention - no matter how wrong - is by now too entrenched in Java culture to ever be changed, so you might as well give up and just call everything get*. This will undoubtedly break some silly library that expects get* to return constant values, but at least you can blame someone else. :D

surya said...

I was thinking about this the other day in REST context ..there should be no difference between an "algorithmic" resource ( total in this case) or a "plain" resource ( name for example).
Client doesn't ( or shouldn't) care how we are "get"ing a resource.
So yeah i would prefer getTotal() in short :)