Google Guava Quickie: Clean toString methods
I’m not very good at debugging code. This is the result of a test infection :). When you do test driven development you don’t need to debug very often. But there are rare cases when I need to start the Debugger. For this task, I love to be able to see speakable representations of the objects in the current scope when it stops at a breakpoint. When I do Java development within Eclipse this can be easily achieved using a Detail Formatter which can be added in the Variables View.
As a result, there is almost no need for me to implement the toString
method of an object. But there is one exception. In concurrent environments where I can’t use the debugger effectively I often go back to old school debugging aka. System.out.println()
. When using this I don’t want to spend too much time implementing the toString
method of an object. I would like to see speakable representations of my objects without implementing a format on my own. The good news is that Google Guava provides a little helper for this that you might not have heard about. It can be found in the [Objects](https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#toString)
class of the base package. Let’s take a look at a toString
implementation using Guava’s toStringHelper
for the Fruit
Class from the last post.
public class Fruit {
private String name;
private String family;
private int calories;
@Override
public String toString() {
return Objects.toStringHelper( getClass() )
.add( "Name", name )
.add( "Family", family )
.add( "Calories", calories )
.toString();
}
}
Instead of using a StringBuilder
or other ugly concatenation methods we can simply call Objects.toStringHelper
and add as many arguments as we want. The output looks like this:
Fruit{Name=A name, Family=A family, Calories=12345}
As the title of this post said, this is really just a quickie, but a useful one from my point of view ;)