JavaAntiPatterns

Collection of bad coding practices

Not taking advantage of ‘toString()’

with 2 comments

Overriding toString() method gives you a cheap way to provide human-readable labels for objects in output. When the objects are used in GUI containers, such as JLists or JTables, it allows to use the default models and renderers instead of writing the custom ones.

Bad:

System.out.println("Author: "+person.getName());

Good:

class Person {
    ...
    public String toString() {
        return this.getName();
    }
}
...
System.out.println("Author: "+person);
Advertisements

Written by Alex

November 22, 2007 at 11:16 pm

Posted in Objects, Strings

Tagged with ,

2 Responses

Subscribe to comments with RSS.

  1. Will u plz provide some detailed explanation on this (regarding use of toString with Swing components)….
    Cheers :)

    khushal

    April 7, 2010 at 4:59 pm

  2. I disagree with this one. toString() should be used for debugging.

    toString doesn’t really describe what exactly is being returned. If toString() was not an inherited override-able method, would you choose the name toString to expose the name? If person’s name was later divided into first, middle, and last – which value would toString return?

    john

    November 17, 2015 at 5:39 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: