Skip to content
Advertisement

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

We have a lot of objects for which we like to implement a simple toString to output attributes of the object. Some of these attributes may be complex objects themselves.

Is there any standard, or simply just a best practice for a style? I’m thinking something like:

[SimpleClassName] { prop1:value, prop2:value }

In which case a nested value would look like:

[SimpleClassName] { prop1:value, prop2:[NestedObject] { prop3:value}}

We are using Java but I find myself asking the same question in most languages!

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement