Google+ Badge

Friday, February 10, 2012

Java needs a toDebugString to go with toString

toString() is a very handy Java method. It allows you and the debugger to display the value of an object in a nice format. The problem is toString() is not just used by the debugger and by your code for logging. This method is used by ListBoxes, Trees, ComboBoxes and other UI elements.

It would be great to add a second method toDebugString() that returns the string to be used by the debugger when inspecting objects and potentially for your logging leaving toString() for UI elements use. In the base Object toDebugString() would return toString() so unless you override toDebugString() they would both act identically. I have various objects that I want to use in a ListBox so I have to use toString() to return a very basic String for a variable usually called name or description. That is great for a ListBox but not for the debugger where I may want to know the name, colors, child count or any number of other things.

I just got done converting some handy debug toString() methods to the much simpler return name; variety in the scheduler code as I needed to show them in the UI. I just lost useful output in the debugger from this. I can easily do my own toDebugString() calls for logging and simple inspection but the Eclipse debugger will not call that when viewing then in a watch list.

Of course Eclipse helps in this area by allowing you to create Detail Formatters. Under Window -> Preferences -> Java -> Debug -> Detail Formatters you can define what you want displayed for various object types. It means you get to go through some extra hoops but you can see the results you want. I really would like to avoid the hoops and have a call right in the code for the object as it is easier to maintain than diving deep into an Eclipse dialog to set things. During initial development I tend to refactor my objects quite a bit.This is not portable to another IDE and if you keep a lot of projects open under a workspace this can get rather cluttered.

I am going to attempt to use the Eclipse Detail Formatters while testing / debugging this project to see how it goes. It could be my fears are unjustified but I really would love a simple / clean solution to this issue easily supported by all IDE / Debuggers.