20

If a String object is immutable (and thus obviously cannot change its length), why is length() a method, as opposed to simply being public final int length such as there is in an array?

Is it simply a getter method, or does it make some sort of calculation?

Just trying to see the logic behind this.

28
  • 6
    Why don't you look at the source and find out?
    – skaffman
    Jan 3, 2012 at 23:40
  • 3
    @skaffman, that wouldn't necessarily explain the design decision. It's a good question, actually. Perhaps you can take a look at the source code and explain why it's length() and not length - I don't see anything to indicate the "why".
    – Paul
    Jan 3, 2012 at 23:48
  • 2
    @Acidic do you want an answer/discussion or do you want to argue about nanoseconds?
    – user949300
    Jan 3, 2012 at 23:54
  • 4
    CharSequence is an example of why their decision was correct.
    – user949300
    Jan 3, 2012 at 23:58
  • 3
    @Acidic The (after the fact) benefit is that you can have multiple implementations of a CharSequence. One of these is StringBuffer, which is obviously mutable, and couldn't use a field to expose its length. This lets you write code that can work with both String and StringBuffer instances transparently. While this isn't common, the Wicket framework uses this in its API.
    – millimoose
    Jan 4, 2012 at 0:05

8 Answers 8

21

Java is a standard, not just an implementation. Different vendors can license and implement Java differently, as long as they adhere to the standard. By making the standard call for a field, that limits the implementation quite severely, for no good reason.

Also a method is much more flexible in terms of the future of a class. It is almost never done, except in some very early Java classes, to expose a final constant as a field that can have a different value with each instance of the class, rather than as a method.

The length() method well predates the CharSequence interface, probably from its first version. Look how well that worked out. Years later, without any loss of backwards compatibility, the CharSequence interface was introduced and fit in nicely. This would not have been possible with a field.

So let's really inverse the question (which is what you should do when you design a class intended to remain unchanged for decades): What does a field gain here, why not simply make it a method?

10
  • 2
    That is an interesting thought. A field, for me, is less code with equivalent - or better performance.
    – Acidic
    Jan 4, 2012 at 0:04
  • 5
    With a tradeoff, of less encapsulation. It can't exist as part of an interface. (Interfaces have constants, but that isn't the same thing) and you can't change your mind about the field. Anyway, any supposed performance benefit is a premature optimization. en.wikiquote.org/wiki/Donald_Knuth
    – Yishai
    Jan 4, 2012 at 0:10
  • "..you can't change your mind.." But if a String is immutable, what else can its number of characters be denoted by other than a final member?
    – Acidic
    Jan 4, 2012 at 0:16
  • 1
    I don't want to sound like a broken record, but I see no reason to implement a method of calculating an accessible (to the String class itself) and constant value. I logically see no reason why a constant should ever be more than it is - a constant.
    – Acidic
    Jan 4, 2012 at 0:28
  • 2
    @Acidic @Inerdial: Even then, don't go for it. Make an accessor method, if for no other reason than for consistency. Why should users of your library have to remember that such-and-such property is a field, but so-and-so is a method? If you want to retroactively add an interface (e.g. CharSequence), why make users wonder what's the difference between length and length()? You can't make all properties be fields, but you can make them all be methods, so just play by good OO rules and use accessor methods unless you have a really good reason to do otherwise.
    – yshavit
    Jan 4, 2012 at 1:46
5

This is a fundamental tenet of encapsulation.

Part of encapsulation is that the class should hide its implementation from its interface (in the "design by contract" sense of an interface, not in the Java keyword sense).

What you want is the String's length -- you shouldn't care if this is cached, calculated, delegates to some other field, etc. If the JDK people want to change the implementation down the road, they should be able to do so without you having to recompile.

4

You should always use accessor methods in public classes rather than public fields, regardless of whether they are final or not (see Item 14 in Effective Java).

When you allow a field to be accessed directly (i.e. is public) you lose the benefit of encapsulation, which means you can't change the representation without changing the API (you break peoples code if you do) and you can't perform any action when the field is accessed.

Effective Java provides a really good rule of thumb:

If a class is accessible outside its package, provide accessor methods, to preserve the flexibility to change the class's internal representation. If a public class exposes its data fields, all hope of changing its representation is lost, as client code can be distributed far and wide.

Basically, it is done this way because it is good design practice to do so. It leaves room to change the implementation of String at a later stage without breaking code for everyone.

4

Perhaps a .length() method was considered more consistent with the corresponding method for a StringBuffer, which would obviously need more than a final member variable.

The String class was probably one of the very first classes defined for Java, ever. It's possible (and this is just speculation) that the implementation used a .length() method before final member variables even existed. It wouldn't take very long before the use of the method was well-embedded into the body of Java code existing at the time.

4
  • 2
    Your original argument holds some water with StringBuffer in place of StringBuilder.
    – erickson
    Jan 3, 2012 at 23:55
  • @erickson: Oh, right! It's been so long since I've used a StringBuffer... thanks. Jan 3, 2012 at 23:57
  • That seems logical, though I would guess that Array was also one of the earliest classes in Java and yet it uses a field instead.
    – Acidic
    Jan 4, 2012 at 0:08
  • 3
    Arrays in Java are special, they're sort of classes but not really. You'll notice that arrays don't have any methods at all. Jan 4, 2012 at 0:10
3

Perhaps because length() comes from the CharSequence interface. A method is a more sensible abstraction than a variable if its going to have multiple implementations.

2
  • 3
    CharSequence was introduced in Java 1.4, long after String was defined. Jan 3, 2012 at 23:48
  • CharSequence came along long after the String API was defined. However, it's a good point, because if length were a field, the String class would have to have been retrofitted with a redundant method in order to support an interface (which specifies methods only). Instance fields are not object-oriented, and should not be part of a public API. Objects that use them, like Point and arrays are old and inconsistent with later work.
    – erickson
    Jan 3, 2012 at 23:52
2

String is using encapsulation to hide its internal details from you. An immutable object is still free to have mutable internal values as long as its externally visible state doesn't change. Length could be lazily computed. I encourage you to take a look as String's source code.

6
  • 3
    I don't see how creating a getter method on a supposedly final variable provides any encapsulation.
    – Acidic
    Jan 3, 2012 at 23:43
  • 1
    The final variable count is internal implementation that it doesn't (and shouldn't) expose. Furthermore, length() is specified by CharSequence, which String implements.
    – Steve Kuo
    Jan 3, 2012 at 23:48
  • If by definition this final int count that you speak of is always equal to the return value of length(), using a method should provide no benefits and only slow down the system. (until it gets inlined, if it does at all)
    – Acidic
    Jan 3, 2012 at 23:52
  • 1
    Bug String doesn't define count, it's not part of String's definition. The purpose of length() is encapsulation. See en.wikipedia.org/wiki/…
    – Steve Kuo
    Jan 3, 2012 at 23:55
  • 1
    As Yishai points out above, CharSequence was made possible in part because String.length() was done this way in 1.0. That's not an accident -- the Java designers knew that exposing methods instead of fields can have those sorts of benefits.
    – yshavit
    Jan 4, 2012 at 0:27
1

Checking the source code of String in Open JDK it's only a getter.

But as @SteveKuo points out this could differ dependent on the implementation.

2
  • what does dependent on implementation means precisely in this case?
    – Acidic
    Jan 3, 2012 at 23:45
  • 3
    I mean that the implementation does not need to be a getter to be compatible with the API.
    – tidbeck
    Jan 3, 2012 at 23:47
1

In most current jvm implementations a Substring references the char array of the original String for content and it needs start and length fields to define their own content, so the length() method is used as a getter. However this is not the only possible way to implement String.

In a different possible implementation each String could have its own char array and since char arrays already have a length field with the correct length it would be redundant to have one for the String object, since String.length() is a method we don't have to do that and can just reference the internal array.length .

These are two possible implementations of String, both with their own good and bad parts and they can replace each other because the length() method hides where the length is stored (internal array or in own field).

3
  • Out of curiosity, what would happen if an implementation had a String type which simply included a char[] and an int (for hashCode), a Tailstring type which derived from String, and included a StartIndex, a HeadString type which derived from string and included a PartialLength, and a SubString type which derived from String and included both? My guess would be that too much code checks to see if something's type is String rather than seeing if it's instanceOf String for that to work, but it would seem to in some ways offer the best of all possible worlds.
    – supercat
    Jan 28, 2013 at 0:09
  • @supercat code checking for String would be a problem. Then there is a slight performance penalty for virtual calls, the jvm has to find out at runtime if it has to call String.length(), TailString.length(), HeadString.length() or Substring.length() instead of just calling String.length() directly (this makes JIT optimizations harder) - so this can be a performance vs. memory footprint decision.
    – josefx
    Jan 28, 2013 at 0:35
  • Well, obviously Java is what it is, but I wonder what would have been the consequences of having string as a compiler-recognized type, whose contents would be encapsulated in a HeapString. Such a thing would have allowed operators like == to perform string comparison when used on the string type; strings could be converted to Object, as with Integer, comparison on strings stored as Object would test reference equality.
    – supercat
    Jan 29, 2013 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.