I know that in Java, it is common practice to use "get" as a prefix to an accessor method. I was wondering what the reason for this is. Is it purely to be able to predict what it is returning?
To clarify: In some java classes (eg String
) a variable like length can be accessed by calling "length()" rather than "size()
". Why are these methods written like this, but others like "getSomeVariable()
"?
Thank you for your time.
Edit: Good to see I'm not alone about the confusion & such about the size and length variables
'get' prefix (or 'is' for methods returning booleans) is a part of JavaBean specification which is used throughout the java but mostly in views in web UI.
length() and size() are historical artefacts from pre-javabean times; many a UI developer had lamented the fact that Collection has a size()
method instead of getSize()
Because properties are nouns and methods are verbs. It is part of the bean pattern that is well-established and therefore expected by anyone using your class.
It might make sense to say:
String txt="I have " + car.GetFuelLevel() + " liters of petrol.";
or ...
String txt="I have " + car.FuelLevel + " liters of petrol.";
but not ...
String txt="I have " + car.FuelLevel() + " liters of petrol.";
I mean, it doesn't make sense to say "Hey, car. Go FuelLevel for me." But to say "Hey, car. Go GetFuelLevel for me." That's more natural.
Now, why did they break rank with String.length() and others? That's always bothered me, too.
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