Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merits/Reasons for using "get" as a prefix in the name of an accessor method

Tags:

java

oop

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

like image 495
bgw Avatar asked Oct 08 '09 22:10

bgw


2 Answers

'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()

like image 155
ChssPly76 Avatar answered Oct 21 '22 10:10

ChssPly76


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.

like image 24
Rap Avatar answered Oct 21 '22 09:10

Rap