views:

216

answers:

5

Is it good or bad practice auto-generating toString methods for some simple classes?

I was thinking of generating something like bellow where it takes the variable names and produces a toString method that prints the name followed by its value.

private String name;
private int age;
private double height;

public String toString(){
   return String.format("Name: %s Age: %d Height %f", name, age, height);
}
+9  A: 

I personally like to implement a toString method for all objects, as it helps in debugging.

I would look into using the Apache Commons ToStringBuilder.

You can implement a simple toString method using reflection as follows:

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

Using this method, you will not have to update your toString method if/when fields are added.

Steve
Though this does have some disadvantages. You have no control over which fields are displayed, and reflection has a reputation for being slow.
Don
+7  A: 

Eclipse 3.5.2 (and possibly earlier versions) already provides this feature. If you right-click within the editor, you'll find it under Source -> Generate toString()...

To answer your question about whether it's a bad practice to autogenerate toString(), my opinion is that it is not. If the generated code is very similar to the code you would have written yourself, then why bother typing it out?

Don
As does IDEA since at least version 8 (although you have to enable the option). You do alt-insert while on the class (or right click and choose Generate).
Yishai
Thanks a lot, that's really handy.
Gordon
IMO, this doesn't answer the question - OP is asking if it's *best practice*, and that wasn't mentioned in this answer..
Jeriko
+3  A: 

To add to Steve's and Don's answers (+1 for them) :

Make your toString() method simple, be careful about not throwing expections in them (specially be aware of fields that could be null) or catching them gracefully.

If possible, don't call other methods of your class in your toString() . At least, take care that your toString() never modifies your object.

And be aware of silly exception-toString loops:

public class MyClass { 
       ... 
       public String toString() { 
          // BAD PRACTICE 1: this can throw NPE - just use field1
            return " field1=" + field1.toString() 
                + " extraData=" + getExtraData();
          // BAD PRACTICE 2: potential exception-toString loop
       }

       public MyExtraData getExtraData() {
           try { 
           .... do something
           } catch(Exception e) {
              throw new RuntimeException("error getting extradata - " + this.toString(),e);
           }

       }

}
leonbloy
A: 

Be clear when adding toString() as to the audience of the generated text. Some frameworks use the toString() method to generate end user visible text (e.g. certain web frameworks), whereas many people use toString() methods to generate debugging / developer information. Either way, make sure that you have enough uniqueness in the toString implementation to satisfy your requirements.

The default JDK implementation of toString() generates developer info, so that's usually the pattern I recommend if possible, but if you are working on a project with a different idea / expectation you could wind up confused...

Will
A: 

If you use lombok they have a @ToString annotation which will generate the toString for you.

The reason why this is much better to use instead of generating toString with eclipse for instance is that if you later add,remove or change attributes of the class, you will also have to regenerate the toString. If you use lombok you don't have to do that.

Shervin