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 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); }
Automatic Call of toString() When a parameter should be a String reference, but is a reference to another type of object, Java calls the object's toString() method to create a String and then uses the resulting String reference.
Your toString() method is actually being called by the println method.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With