[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: The right way(tm) of writing toString() (Was: Re: [PATCH] Field posi

From: Etienne Gagnon
Subject: Re: The right way(tm) of writing toString() (Was: Re: [PATCH] Field position attribute handling)
Date: Sat, 29 Nov 2003 14:42:57 -0500
User-agent: Mozilla/5.0 (X11; U; Linux ppc; en-US; rv:1.5) Gecko/20031110 Debian/1.5-3

Dalibor Topic wrote:
e) use '+' to concatenate strings and objects

Rationale: Most Java compilers can optimize string concatenation by using string buffers. There is no need to do that task by hand. Using '+' allows you to write simpler code.

I partly disagree.  When you iterate through a collection, using "+" will
create one stringbuffer per iteration => bad.

So, I would in fact recommend using stringbuffers everywhere, unless the
toString() body holds on a single source line.

f) don't use toString() on non-primitive fields. Use "field_name=" + field instead.


g) don't write special code to handle fields being null

I think it also works for sb.append().

Example code:

public class Test{
  private String field_1;
  private int field_2;

  public String toString() {
    return ("Test
            + "[field_1=" + field_1
            + ", field_2=" + field_2
            + ']');

This is a "logical" single line, so it fits the non-StringBuffer thing.  But,
this does not work for LinkedList.toString(), for example.


p.s. if performace of toString() doesn't matter that much, and we can use reflection

No, please!  We want toString to be fast.  It is part of the base functionality
of Object(), so there is no reason to assume programmers will only use it for


Etienne M. Gagnon, Ph.D.   

reply via email to

[Prev in Thread] Current Thread [Next in Thread]