Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How important are naming conventions for getters in Java?

I’m a huge believer in consistency, and hence conventions.

However, I’m currently developing a framework in Java where these conventions (specifically the get/set prefix convention) seem to get in the way of readability. For example, some classes will have id and name properties and using o.getId() instead of o.id() seems utterly pointless for a number of reasons:

  • The classes are immutable so there will (generally) be no corresponding setter,
  • there is no chance of confusion,
  • the get in this case conveys no additional semantics, and
  • I use this get-less naming schema quite consistently throughout the library.

I am getting some reassurance from the Java Collection classes (and other classes from the Java Platform library) which also violate JavaBean conventions (e.g. they use size instead of getSize etc.).

To get this concern out of the way: the component will never be used as a JavaBean since they cannot be meaningfully used that way.

On the other hand, I am not a seasoned Java user and I don’t know what other Java developers expect of a library. Can I follow the example of the Java Platform classes in this or is it considered bad style? Is the violation of the get/set convention in Java library classes deemed a mistake in retrospect? Or is it completely normal to ignore the JavaBean conventions when not applicable?

(The Sun code conventions for Java don’t mention this at all.)

like image 436
Konrad Rudolph Avatar asked Sep 07 '09 12:09

Konrad Rudolph


1 Answers

If you follow the appropriate naming conventions, then 3rd-party tools can easily integrate with and use your library. They will expect getX(), isX() etc. and try to find these through reflection.

Although you say that these won't be exposed as JavaBeans currently, I would still follow the conventions. Who knows what you may want to do further down the line ? Or perhaps at a later stage you'll want to extract an interface to this object and create a proxy that can be accessed via other tools ?

like image 96
Brian Agnew Avatar answered Oct 21 '22 07:10

Brian Agnew