Item 10: Always override toString

Providing a good toString makes your class pleasant to use.
Not only the users of your class will love using the toString method, even the debuggers IDEs use the toString method of your object.
e.g. Which would you rather see when printing a map, “{Jenny=PhoneNumber@163b91}” or “{Jenny=(707) 867-5309}”

When practical, the toString method should return all of the interesting information contained in the object
It makes sense to display the whole phone number at once. Missing out the area code or the state code will not make any sense.

Whether or not you decide to specify the format, you should clearly document your intentions.
If your toString method is subject to change, it is always helpful to comment and document everything in your java doc. Now, even if you change the format or something of your toString method, the programmer using your toString, will have no one to blame but himself for not reading the documentation.

Provide programmatic access to all of the information contained in the value returned by toString
This is important as even if there is a change in the toString implementation, all the information available through toString will also be available through other accessor methods.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: