Wednesday 20 May 2009

Java Tips - Always Override toString()

I am sure all of us at some point in time of our software development career, would have done an SOP on an object, expecting to see an interpretable string value but were displayed a string, which could not add much to our understanding.

Though java.lang.Object provides a default implementation of toString() method, I dont think its really informative. The returned string consists of the class name followed by an @ sign and an unsigned hexadecimal representation of the hash code, for example, Employee@235b92.

Actually The contract for the toString() method says that the returning string sould be concise, easily readable and also all the subclasses should override it. Though it can be argued that Employee@235b92 is concise and small enough to read, but it certainly is not very informative.

Joshua Bloch suggests to override toString() method so that a suitable string interpretation of your object can be returned. Providing a good string implementation makes your class much more pleasant to use. Overriding toString() appropriately not only is beneficial to instances of your class, but it is also useful for the objects containing instances of your class. For example if you want to print the contents of a hashmap containing instances of your class, I am sure anyday you would prefer to see a Employee@BillGates_CTO over Employee@235b92.

Ideally, the toString() method should contain all the interesting information about the object. But if the object is really large it might not be possible to include all the information in returning string. In that case you can make it return something which provides a small summary of the object.

I know that you are not really familiar with this approach and might not find it a value adding practice but I would still recommend that you start using it and I am sure that soon you would start appreciating it's benefits.

No comments:

 
Technology