I would like to make this que开发者_高级运维stion Java related cause it's why I started to wonder about it. I always read it's preferable to use getters/setters or other methods to encapsulate the internal structure of a class. But in Java, when we want to get a length of an array we have to access a field member length
of it, ie. new String[] {""}.length
. Can someone please explain me why the creators of Java have decided to do it in this way? And are there any other situations where such a solution is better than accessing a member throught a method call?
The answer is that there is no reason. Just because you were involved in the writing of an API doesn't mean you automatically make the best decisions.
Groovy, for example, added .size()
everywhere .length()
or .length
was before to standardize the way you asked for an objects size. Why the heck should .length
work on arrays on .size()
work on lists? That just doesn't make sense.
Languages like Groovy and C# let you define properties, as well, which mitigate this sort of method-or-no-method nonsense.
obj.a = 5
In Groovy/C#, that could be calling obj.setA()
, but as the caller, should you really care?
I know I'm stating the obvious, but it is a matter of safety (don't throw any rocks). With regards to the array length field being directly accessible. I assume it was coded that way to provide convenience, it is still safe because the length is defined as final and can't be modified. If a particular field isn't final, then making it public would allow something external to class to modify it without the classes knowledge.
I realize that is all pretty rudimentary stuff, I probably could have just said that the array length is final, which allows it to safely be public
Back then, runtime optimization wasn't good, method calls were expensive, this would suck:
for(int i=0; i<array.length(); i++)
That can be a killer argument. But maybe the first thing they considered was aesthetics.
If you are writing a small peace of code for your own you may do what you want, nothing is right or wrong, but if you want to write an API and you want the freedom to change implementation without changing the API it's better to use getters/setters.
Reading from field you can't get a value that is calculated on the fly or make it lazily initialized. Writing to a field you can't, for example, notice listeners.
精彩评论