ToString (): for debugging or for people?

class Address
{
  private enum Component
  {
    NUMBER,
    STREET,
    STATE,
    COUNTRY
  }

  private Map<Component, String> componentToValue = ...;
}

I would like my class to contain two methods:

  • One to indicate the value of each component of the address (so I can debug if something goes wrong).
  • One to return the address in the form expected by the people: "1600 Amphitheater Parkway Mountain View, CA 94043."

What is the best practice for Object.toString ()? Is this primary for # 1 or # 2? Is there a best practice to label these methods?

+5
source share
7 answers

Format the address in the same way in the SMS message and on the HTML page? Would you format it also in English, French and Japanese?

, : , , . , , HtmlI18nedAddress, toString .

Date vs SimpleDateFormat. Date SimpleDateFormat .

+13

, . ToString() .

: ToString(), Parse ( ) ( , ). , , , ToString().

+3

, .:

@Override
public String toString() { 

    if(debug) {
        return debugAddrString()
    }
    return normalAddrString();

}
0

ToString . , Object; Object ? , , , . .

: IDE ToString .

0

, , Debug, , :

public String toString(boolean debug) {
    if (debug) return debugStringVersion;
    else return humanVersion;
}

public String toString() {
    return toString(Util.DEBUG);
}

Of course, this assumes that you have a utility class with a debug flag in it.

-1
source

Javadoc says:

In general, the toString method returns a string that "textually represents" this object. should be a concise but informative presentation that is easy for a person to read.

So I go with 2.

-1
source

All Articles