Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is length used as a method and when as property in Java? [closed]

Tags:

java

object

I've seen some legacy code that uses lengthproperty on some objects and others that uses length() method. Currently I'm working with a NodeList from the org.w3c.dom package and I found that it have the getLength() method to get the numbers of elements.

My Question is how as Java developer I can know how to determine when to use length, length(), size(), getLength()? obviously it depends of the object type and the API is there for read... but the point is how the Java Development select which of that implements in their classes.

Note: In the Question When to use .length vs .length() Makoto answer's indicates that .length is a property on arrays. That isn't a method call, and length() is a method call on String. But, why is the reason? why not use ever a method or ever a property for maintain the consistency around all the API.

like image 273
PlainOldProgrammer Avatar asked Dec 16 '14 18:12

PlainOldProgrammer


2 Answers

how would Java developers select which of [the methods] to implement in their classes?

When you implement classes that contain other objects, it's almost always going to be size(), the method provided by theCollection interface.

As far as other choices go, you should avoid exposing member variables, even final ones, because they cannot be accessed through an interface. Java gets away with it for arrays because of some JVM trickery, but you cannot do the same. Hence, length should be out: it remains in Java because it's not possible to change something that fundamental that has been in the language from day one, but it's definitely not something one should consider when designing new classes.

When you implement your own type that has length (say, a rectangle or a line segment) you should prefer getLength() to length() because of Java Beans naming conventions.

like image 67
Sergey Kalinichenko Avatar answered Oct 23 '22 14:10

Sergey Kalinichenko


obviously it depends of the object type and the API is there for read...

You already have answered your question yourself: look in the API documentation of whatever class you are using.

but the point is how the Java Development select which of that implements in their classes.

The classes in Java's standard library have been developed over a long period of time by different people, which do not always make the same choice for the name of methods, so there are inconsistencies and unfortunately you'll just have to live with that.

like image 5
Jesper Avatar answered Oct 23 '22 12:10

Jesper