Is it good or bad practice auto-generating toString
methods for some simple classes?
I was thinking of generating something like below where it takes th
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.
Just noticed -In NetBeans IDE you can generate toString() method by selecting fields you want to generate it for right click->insert code
or use shortcut ALT+INSERT
and then select toString().
Way it looks is :
@Override
public String toString() {
return "ClassName{"+"fieldName="+fieldName+'}';
}
Its great way to debug and no need for additional libs.
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?
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...
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.