Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toString(): for debugging or for humans?

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

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

I'd like my class to contain two methods:

  1. One to indicate the value of each address component (so I can debug if anything goes wrong).
  2. One to return the address in a form expected by humans: "1600 Amphitheatre Parkway Mountain View, CA 94043".

What is the best-practice for Object.toString()? Is it primary meant for #1 or #2? Is there a best-practice for the naming of these methods?

like image 213
Gili Avatar asked Jan 21 '11 18:01

Gili


2 Answers

Would you format an address the same way in a SMS message and in an HTML page? Would you format it the same way in English, French and Japanese?

If no, then you have your answer : the presentation does not belong to the object, but to the presentation layer displaying the object. Unless the object is specifically made up for the presentation layer, for example if it is a HtmlI18nedAddress, use toString for debugging.

Consider Date vs SimpleDateFormat. Date contains the state and SimpleDateFormat returns multiple representations.

like image 199
JB Nizet Avatar answered Sep 24 '22 15:09

JB Nizet


I would say the first. Data formatting should not be hard coded into the ToString() function of the object.

I look at it this way: I try to make my ToString() output data that is readable by a matching Parse(string data) function (if that function actually exists or not is not important). So in this case, if you want a specific formatting, write a specific function, and leave the generic data dump routines to ToString().

like image 20
Timothy Baldridge Avatar answered Sep 23 '22 15:09

Timothy Baldridge