Thursday 27 November 2008

Item 10: Always Override toString

So, on to item 10, "Always override toString()". Quite a short and simple item this one, the author's arguments for this is that it is convenient for describing objects in print statements and similar, and for displaying objects in debuggers. Another case not explicitly mentioned is in logging statements. I agree that this is good advice, even though I must admit to not doing as often as I probably should myself.

The default implementation in Object is usually not very helpful - though it does show which instance of an object that is referenced, something other examples usually don't. I guess there may be cases when debugging logs for example when this is useful. Anyway, the author goes on to describe what makes a good implementation of toString(): ideally describing as much as possible of the object, though for some objects a descriptive summary will have to do.

Finally, there's a discussion about whether the details of the format returned by toString() should be specified, so in effect becoming part of the public API of a class. Examples where this is done include the boxed primitive types. Another example is java.util.Date. I can't help thinking that this is the exception rather than the rule, and really just applies to very simple value objects. And I can't see myself adopting the author's suggested JavaDoc format for documenting toString(), that seems over the top for most cases.

Actually, this last point reminds me of an impression I've had with a few of the items in this book: they seem to be advice that makes sense for someone implementing widely used library code (as Mr. Bloch has done of course, his name is all over the base Java libraries), but makes less sense for application developers for example. Is that a fair comment to make?

Jan Stette

No comments: