Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : naming convention for accessors

I'm looking for the official naming convention in Java regarding accessors.

I've seen that, for instance, the JPanel class deprecated the size() method in favor of getSize().

But in the ArrayList class, the method is size().

So I'm wondering if accessors should be named getXXX() or xXX() ?

like image 535
Jérôme Avatar asked Sep 13 '10 06:09

Jérôme


People also ask

How should accessor methods be named?

Naming Conventions Given a property of type type and called name , you should typically implement accessor methods with the following form: - (type)name; - (void)setName:(type)newName; The one exception is a property that is a Boolean value.

Which conforms to the naming convention of Java accessor methods?

CamelCase in Java naming conventions Java follows camel-case syntax for naming the class, interface, method, and variable.

What are the naming conventions for accessor methods and mutator methods in Java?

Accessor method signatures should always look like public Type getProperty() . Additionally, accessors should always return a copy of the property's value, not the value itself. Mutator method signatures should always look like public void setProperty(Type value)


1 Answers

It's usually a bad idea to not use the JavaBeans convention (getters and setters).
They're used through reflection by many frameworks, in particular with EL where sometimes you can't access your fields without the rights getters (depending on the EL flavour).

So your accessors should always be named getXxx() or isXxx() and setXxx().

size() in the collection framework is an example of "flaw" which can annoy developers (see link below). The choice made by Josh Bloch and Neal Gafter to make it more readable now makes it difficult to obtain in some contexts (EL).

But remember the JavaBeans convention isn't the Java naming convention.


Resources :

  • How to Access the Size of a Collection in a JSP Page Using JSTL-EL
  • Java conventions
  • JavaBeans
  • JavaBeans specification

On the same topic :

  • Getters on an immutable type
like image 52
Colin Hebert Avatar answered Sep 28 '22 04:09

Colin Hebert