We have toString() method since Java 1.0
It has at least two different meanings:
Displaying: How the object should appear to the user, in the GUI, on a web page, etc. Inspection: How the object should appear in debug output, logs, debugger tools etc. Both are in some way “a string representation of the object”. The default implementation in java.lang.Object suggests inspection, e.g. “java.lang.Object@c37f31”, but many APIs, like AWT/Swing, use it for displaying the object to the user.
Problems: It’s hard to tell which usage is intended when reading the code. Debuggers will use toString(), which can cause confusing side-effects. Since every object has a toString(), the IDE’s usage search becomes unusable. It’s hard to tell if a toString() method is dead code or not. We can’t do much about java.lang.Object, but we still have options.
Suggestion: Use toString() only for logging and debug output.
If the method has a more specific meaning, communicate that instead, e.g. title() or name().
If the value to display has a specific format you can communicate that instead, e.g. toHTML() or asLeetSpeak().
If the value to display is nothing other than a string, still avoid toString(). Call it something like displayString(), or maybe even asString() to avoid problems.
Reference: http://java.sun.com/
Tuesday, February 03, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment