Difference between getter method and method that returns the state of an instance variable?
I am reading the Guava library and I keep using methods that look something like this:
@Override public int size() {
return size;
}
What is the difference (strategically, conventionally, etc.) between the above and the following?
@Override public int getSize() {
return size;
}
Or is there no difference? Is it just a shorthand?
source to share
One form does not use JavaBeans conventions . Functionally speaking, systems that expect you to follow these conventions won't work or be very cumbersome to configure if you use unconventional getters / setters for your beans, but if you don't, then there is no real difference.
Since Guava has many collections, and an interface Collection
actually defines a size()
method , my gut tells me that Guava is more inclined to follow the interface Collection
than the JavaBeans conventions.
source to share
- In terms of performance, there is no difference.
- From a readability standpoint, they are also similar, but
getAttribute
says more about what this method does (size
could mean we need to do some extra computation, in most cases getters just return a value). - But I suspect that the main reason people tend to refer to their methods as get / set ... is to allow their class to become a proper JavaBean that will be properly handled by tools using JavaBeans like Expression Language .
Anyway, about your example. I suspect that since List
it shouldn't be seen as JavaBean
, there is no need to return size
with getSize()
, so a simple one is sufficient size()
.
source to share