This post originated from an RSS feed registered with Java Buzz
by Sam Dalton.
Original Post: The Abuse of toString()
Feed Title: import java.*;
Feed URL: http://www.samjdalton.com/pebble/rss.xml
Feed Description: Random, Infrequent Bloggings of a Techie
Found this on someone elses blog, and thought that I would repost it here (mainly so that I can find it again in the future!)
8<--------------CUT HERE------------------>8
The abuse and over-use of toString()
This one is sneaky.. most programmers when writing debug code tend to call the toString() method on an object to retrieve human-readable information and present it to the user in some shape or form (logs, system out, etc). That's good programming.. when debugging a problem we want to be able to read and view all information possible..
Here is the sneaky part.. you should never *never* call toString() on a Java object unless you're pretty damn sure that object will never be null. Why? It's simple.. calling toString() on a null object will generate our good old friend -- the null pointer exception. (What? Java has no pointers! -- wrong!). This is a huge problem.. Think about it.. where do we usually put most of our debugging code? That's right.. error handling.. Something like this, perhaps:
try
{
myObject = doSomething();
}
catch (HorribleException e)
{
String msg = "Dude, we got us a problem: " + e.getMessage();
msg += "The object looks like this" + myObject.toString();
// do logging and stuff..
//
}
If myObject happens to be null, which may very well be the case considering we have an exception while trying to create, modify or reference it it will throw a null pointer exception at which point this becomes a debugging nightmare as the original exception is now lost. Maybe not a huge nightmare in a development environment.. but try to debug issues with code like this in a production environment where all you have to go on is logs and system output. Right.. nightmare.
What should you do instead? Forget toString()! There is a better way of doing it and that's String.valueOf(object) which is implicitly called on calls that convert objects to strings. String.valueOf(object) internally calls toString() on the object -- but it checks for nulls! This is the behaviour you want in your debugging code.. if the object is null you do not want an exception.. just a "null" ought to suffice and the toString() output otherwise..
try
{
myObject = doSomething();
}
catch (HorribleException e)
{
String msg = "Dude, we got us a problem: " + e.getMessage();
msg += "The object looks like this" + myObject;
// do logging and stuff..
//
}
Will generate exactly the same output as the first example when object is fine.. but only the string "null" when object is null. Safer and even less typing! The scary part is how many experienced programmers have no clue about this little gotcha.. go spread the word. Thanks.