18

Lets face it writing nice toString messages is a boring messy chore that needs to be done as it can really be helpful for insepection in a debugger or logging.

What features do you like or wish should be in such a helper...

  • dumping properties should come w/ labels.

    name=mP country=Australia ...

  • values that are some default should optionally be skipped.

    • Theres no point printing lots of properties that are 0 or null.
    • If you set a label and the value is null dont include either.
  • the seperator between label and value should be updatable and it should auto be inserted between labels and values when they are added.

  • it should also auto insert the separator of your choice.

    If you want commas spaces whatever between values when including an array so be it.

  • it should auto quote string values...because its important to know exactly where a string starts and ends.

    *name=mP state="New South Wales"

  • when a list, map or set is added the rules about quoting strings, using the set separator etc should be respected. Please dont just dump Collection.toString().

I have a few others in someting i am improving can you list your own ideas, observations etc.

  new ToStringBuilder()
    .setLabelValueSeparator('=')
    .label("name")
    .value(Country.AUSTRALIA) // -> returns "Australia" without the quotes.
    .label("day of death")
    .value(null) //
    .label("numbers")
    .valueSeparator(",");
    .value(Arrays.asList( 1, 2, 3 )
    .build();

will of course result in "name="Australia" numbers=1, 2, 3;

mP.
  • 18,002
  • 10
  • 71
  • 105

2 Answers2

22

Apache ToStringBuilder has a decent implenentation out of the box:

@Override
public String toString() {
  return ToStringBuilder.reflectionToString(this);
}

I'm actually looking right now on how to get its output to be a bit prettier. ReflectionStringBuilder seems to offer some more customization. Specifically I like this:

@Override
public String toString() {
    StandardToStringStyle style = new StandardToStringStyle();
    style.setFieldSeparator(", ");
    style.setUseClassName(false);
    style.setUseIdentityHashCode(false);

    return new ReflectionToStringBuilder(this, style).toString();
}

The output looks like this:

[email=foo@gmail.com, age=16, createdDate=<null>, favoriteColor=blue, id=2]
patstuart
  • 1,931
  • 1
  • 19
  • 29
ripper234
  • 222,824
  • 274
  • 634
  • 905
9

I just use my IDE to generate the toString for me. If I change the code, I delete the method and regenerate.

Michael Barker
  • 14,153
  • 4
  • 48
  • 55
  • 1
    Yeh but generated toStrings suck, they have all the weaknesses described in the q. – mP. Jan 21 '11 at 09:24
  • I was alluding to the fact that it is just not that important. `toString()` is simply a debug mechanism to allow the viewing of the state of a class. Data presentation should be done by some sort of externalised formatter. If you are using `toString()` for anything else, then I think you've got your design wrong. – Michael Barker Jan 21 '11 at 17:32
  • 3
    You can do such better than generated toStrings, so why not go that bit further and write a proper toString that is meaningful rather than dumping every field possible. There are so many weaknesses w/ this approach its not funny. Imagine if String.toString took this approach we would have some ugly char[] dump ot an array with individual chars dump. – mP. Jan 23 '11 at 00:43
  • Good documentation and a good toString, meaningful exception messages they are easy to do, and save lots of time not only for youself but future lookers of the code. IHow hard is it to write a nice message when a parameter is null rather than just letting the code blow up with a NPE w/ no message ? – mP. Jan 23 '11 at 00:45
  • Nice toStrings also mean that your objects are ready for logging. If your tooString is nice, then you dont need to build up a dump when logging at each and every spot you log might include some class - its already done for you. Overall it means yout stuff is that little better, coding is a headache as it is, its the little things like this that make life a bit easier. – mP. Jan 23 '11 at 00:47
  • Because you're painting the bike shed. Generated toString methods give you all of the information that you need with basically no effort - they may not be perfect, but I've never found them lacking information. I have far more important things to spend my time on. – Michael Barker Jan 23 '11 at 06:12