Why is String.length() a method?

后端 未结 8 757
难免孤独
难免孤独 2020-11-30 10:34

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 lengt

8条回答
  •  有刺的猬
    2020-11-30 10:43

    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.

提交回复
热议问题