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!
Not a direct answer to the question, however below would be a time saver during initial development:
Disclaimer: Apache Commons library is used.
xreflect
inJava > Editor > Templates
; Add below into its pattern textarea:OK
,OK
xreflect
and press Ctrl + Space to autofill equals(), toString() and hashCode() methods automatically.json syntax seems to fit pretty well since it was designed specifically to represent complex objects as strings
If your objects have something that might be useful as an identifier, I'd implement something like your second example:
Where the
id
is whatever makes sense for that object to be an identifier - the name for the canonicalPerson
object, a primary key for an object from a database, etc.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):
There's also the possibility to add an identifier with
@
, for example the default style for the commons-langToStringBuilder
does that (using its own example):check out phps print_r($obj, true) or also serialize() could work, dont know exactly for what its needed for. jsons is also a clean solution, especially if u want to import the data in javascript environbments
No. The "best" output for a
toString()
method is determined by what you want to use it for. Is it for serializing the object state in a form that allows it to be deserialized? Is it for creating debug messages? Is it for rendering the object for display to end-users?If you want to develop an in-house style for your debug/logging
toString()
methods, that's fine. But unless there was a requirement for this, I wouldn't bother. IMO, it is effort that could better be spent elsewhere.