KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
It is consistently advised to override (implement) the toString() method of a class. The Java API documentation itself says "It is recommended that all subclasses override this method.". Bloch, in Effective Java has the item "Always override toString". And only a fool contradicts Bloch, right? I am however coming to doubt this advice: is it really worth implementing toString() for entity classes ? I'll try to lay out my reasoning. An entity object has a unique identity; it is never the same as another object, even if the two entites have equivalent attribute values. That is, (for non-null x ), the following invariant applies for an entity class (by definition): x.equals(y) == (x == y) The toString() method returns a string that "textually represents" its object (in the words of the Java API). A good representation captures the essentials of the object, so if two representations are different they are representaions of different (non-equivalent) objects, and conversely if two represenations are equivalent they are representations of equivalent objects. That suggests the following invariant for a good representation (for non-null x , y ): x.toString().equals(y.toString()) == x.equals(y) Thus for entities we expect x.toString().equals(y.toString()) == (x == y) that is, each entity object should have a unique textual representation, which toString() returns. Some entity classes will have a unique name or numeric ID field, so their toString() method could return a representation that includes that name or numeric ID. But in general, the toString()</code
Tags (comma-separated)
Save Edits
Cancel