Reputation: 16212
Through the Java API you see numerous occurrences of conflicting naming and practices which are really confusing to me.
For example:
The String class has a private variable (Integer) by the name of count
which keeps track of the size of the string, however this is returned by a getter by the name of length()
.
If you move over to any type of arrays, instead of having a getter method for length, they just pass the variable through with a public accessor, and it can be obtained through arrayInstance.length
.
Moving back to the String class we have the String#getBytes()
method which is a getter, similar to the length()
getter, however performs slightly more logic to get and return the value.
To me, personally, creating a getter with the prefix of get
seems redundant, for example I rather type GamePacket#data()
versus GamePacket#getData()
however I feel like there may be a deeper meaning behind this naming instead of just inconsistency.
Also, why doesn't the Array[]
use a getter for length
?
Would anybody be kind enough to shed some light on this for me?
Upvotes: 10
Views: 602
Reputation: 34648
This is not going to be a full answer, as a real answer would probably require interviewing the original developers of Java or otherwise researching historical records. But here are a few notes:
length
field of an array is final
, therefore it cannot be set.String
class were designed in the earliest versions of Java, before the conventions for getters and setters were settled upon. The get...
is...
and set...
conventions have only really been settled upon at the introduction of JavaBeans. Changing the API would make old code stop working, and so the old names persist.Upvotes: 1
Reputation: 692281
Getters (and setters) come from the Java Bean specification. The reasons to use them are multiple:
get
CtrlSpace to discover all the information available in an object.You usually name the getter the same way as the private variable that holds the information, but what matters is encapsulation and the public API, so nothing prevents you from computing a value in a getter, or to name the private field a different way.
Upvotes: 6
Reputation: 8202
Naming conventions appear to vary throughout the Java codebase, but one early standard was the JavaBeans naming convention; this basically formed an nomenclature solution to Java's lack of true properties.
Object/primitive getters had the form getXXX(), except for booleans, which had the preferred form isXXX(). Setters were always in the form setXXX().
From this single point, millions of lines of reflective code were written.
This convention pre-dated annotations, which would have been a trade-off between increased intent and increased verbosity when writing something like this pseudo-ish code
@Setter
void data(Data data) {
this.data = data;
};
@Getter
Data data() {
return data;
};
Upvotes: 0