Will Clausen's Website

Categories
WCW

Effective Java: Item #10

Item #10: Always override toString

All classes that extend the Object class, which is to say all classes, have the toString method. When toString is not overriden, this method simply prints the name of the class, followed by an “@”, followed by the id of the instance of the class. This is not super helpful to people using your class and trying to debug.

So, as a means of providing useful information about the class in an easily accessible way for people using your class, you must always override toString.

There are some important considerations that go into overriding toString. First, the method should return all of the interesting information in the object. In the event that there are a huge number of member variables, toString should print a summary of the object.

Another important consideration is whether to specify the format of the particular toString implementation you decide to use. Keep in mind that if you do, you are stuck with that format forever, as changing it would break code that uses your class and that method. Whatever you decide when it comes to specifying a format, you must document it, so that users of the class can have a clear understanding of what they can expect.

Finally, you should make sure to provide access to all of the important information returned by toString. Otherwise, users of your class have to parse the toString, reducing performance and increasing hassle.

 

Leave a Reply

Your email address will not be published. Required fields are marked *