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.

or sb.append("field_name="); sb.append(field);

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.

Etienne

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 debugging.

Etienne

--
Etienne M. Gagnon, Ph.D.             http://www.info.uqam.ca/~egagnon/
SableVM:                                       http://www.sablevm.org/
SableCC:                                       http://www.sablecc.org/



_______________________________________________
Classpath mailing list
[EMAIL PROTECTED]
http://mail.gnu.org/mailman/listinfo/classpath

Reply via email to