Always override toString

While java.lang.Object provides an implementation of the toString method, the string that it returns i generally not what user of your class wants to see. It consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, for example “PhoneNumber@163b91”.

While it could be argued that “PhoneNumber@163b91”. is concise and easy to read, it isn’t very informative when compared to “(707) 867-5309”. The toString contract goes on to say, “It is recommended that all subclasses override this method.”.

While it isn’t as important as obeying the equals and hashCode contracts, providing a good toString implementation makes your class much more pleasant to use. The toString method is automatically invoked when an object is passed to println, printf, the string concatenation operator, or assert, or printed by debugger.

When practical, the toString method should return all of the interesting information contained in the object, it is impractical if the object is large or if it contains state that is not conducive to string representation. Under these circumstances, toString should return a summary such as “Manhattan white page (1487536 listings)” or “Thread[main, 5, main]”. Ideally, the string should be self-explanatory.

One important decision you’ll have to make when implementing toString method is whether to specify the format of the return value in the documentation. It is recommended that you do this for value classes, such as phone numbers. The advantage of specifying the format is that it serves as a standard, unambiguous, human-readable representation of the object. This representation can be used for input or output and persistent human readable data objects.

The disadvantage of specifying the format of the toString return value is that once you’ve specified it, you’re stuck with it for life, assuming your class is widely used. Programmers will write code to parse the representation, to generate it, and to embed it into persistent data. If you change the representation in a future release, you’ll break their code and data, they will yowl.

Whether or not you decide to specify the format, you should clearly document your intentions. If you specify format you should do so precisely.

Whether or not you specify the format, provide programmatic access to all of the information contained in the value returned by toString.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest sit folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.