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()
?
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.
CamelCase in Java naming conventions Java follows camel-case syntax for naming the class, interface, method, and variable.
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)
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 :
On the same topic :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With