Multiple toString methods?

10,023

There ought to be a separate object to handle formatting. That's why you see formatting objects for dates and numbers in java.text, because there are so many different formats, you need dedicated formatters separate from the data objects.

Looking into what toString is for, the description given in the javadoc is

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The Odersky/Spoon/Venners book Programming in Scala says:

The result of toString is primarily intended to help programmers by providing information that can be used in debug print statements, log messages, test failure reports, and interpreter and debugger output.

Also Effective Java (Item 10: Always Override toString) seems to assume that the purpose of toString is to provide diagnostic information to developers when debugging or logging.

I'd keep the implementation of toString you use for debugging and create a separate CSV-formatting object to deal with the csv generation. That way toString's purpose continues to be for debugging, separation of concerns is maintained between the object's job as a dataholder and CSV-generation.

Share:
10,023
prabu
Author by

prabu

Updated on June 14, 2022

Comments

  • prabu
    prabu about 2 years

    I had a problem in generating a comma seperated string from a list of objects. The problem is explained in this link Convert string in list objects to comma separated

    I had solved this by using toString method. Previously i was using the toString() method as string builder for debugging purpose. As i am using it for the generation of comma seperated value i could not debug it as before.

    Is there anyway to accomplish both?