Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 862
Nicole Avatar asked Oct 15 '10 22:10

Nicole


People also ask

What is the default implementation of toString in Java?

By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.

How is toString implemented?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called. Here are some of the advantages of using this method.

What type of method is toString ()?

What is toString()? A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

Should toString return or print?

toString() is supposed to return a string containing a "description" of the object. It's not supposed to print anything.


2 Answers

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}" 
like image 102
ColinD Avatar answered Sep 30 '22 19:09

ColinD


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] 
like image 41
Wouter Coekaerts Avatar answered Sep 30 '22 17:09

Wouter Coekaerts