What is the best standard style for a toString implementation? [closed] What is the best standard style for a toString implementation? [closed] java java

What is the best standard style for a toString implementation? [closed]


I think the format produced by Guava's MoreObjects.toStringHelper() is pretty nice, but it's mainly just good to have some consistent format that you use:

public String toString() {  return Objects.toStringHelper(this)      .add("prop1", prop1)      .add("prop2", prop2)      .toString();}// Produces "SimpleClassName{prop1=foo, prop2=bar}"


Personally, I find the mix of [] and {} not so easy to get an immediate view of the hierarchy.

I like this format (and I've seen it being used in a number of places):

SimpleClassName[prop1=value, prop2=value]SimpleClassName[prop1=value, prop2=NestedObject[prop3=value]]

There's also the possibility to add an identifier with @, for example the default style for the commons-lang ToStringBuilder does that (using its own example):

Person@182f0db[name=John Doe,age=33,smoker=false]


json syntax seems to fit pretty well since it was designed specifically to represent complex objects as strings

Person = {    "firstName": "John",    "lastName": "Smith",    "age": 25,    "address":     {        "streetAddress": "21 2nd Street",        "city": "New York",        "state": "NY",        "postalCode": "10021"    },    "phoneNumber":     [        {            "type": "home",            "number": "212 555-1234"        },        {            "type": "fax",            "number": "646 555-4567"        }    ]}