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, whichtoString()
returns. Some entity classes will have a unique name or numeric ID field, so theirtoString()
method could return a representation that includes that name or numeric ID. But in general, thetoString()
method does not have access to such a field.Without a unique field for an entity, the best that
toString()
can do is to include a field that is unlikely to be the same for different objects. But that is exactly the requirement ofSystem.identityHashCode()
, which is whatObject.toString()
provides.So
Object.toString()
is OK for an entity object that has no data members, but for most classes you would want to include them in the text representation, right? In fact, you'd want to include all of them: if the type has a (non null) data member x, you would want to includex.toString()
in the representation.But this creates a problem for data members that hold references to other entities: that is, which are associations. If a
Person
object has aPerson father
data member, the naive implementation will produce a fragment of that person's family tree, not of thePerson
itself. If there are two-way assocaitions, a naive implementation will recurse until you get stack overflow So maybe skip the data members that hold associations?But what about a value type
Marriage
havingPerson husband
andPerson wife
data members? Those associations ought to be reported byMarriage.toString()
. The simplest way to make all thetoString()
methods work is forPerson.toString()
to report only the identity fields (Person.name
orSystem.identityhashCode(this)
) of thePerson
.So it seems that the provided implementation of
toString()
is actually not too bad for entity classes. In that case, why override it?
To make it concrete, consider the following code:
public final class Person {
public void marry(Person spouse)
{
if (spouse == this) {
throw new IlegalArgumentException(this + " may not marry self");
}
// more...
}
// more...
}
Just how useful would an override of toString()
be when debugging an IlegalArgumentException
thrown by Person.marry()
?
I always use toString() for my own purposes and not because of some technical requirement. When I have a Person class then the toString method returns the name of the person. No more, no less. It's not unique but for debugging purposes it is enough to see what person is meant. Especially in web development this comes in very handy when I just have to write the object name in JSPs to get the name of the person so I know I have the correct object.
If the object has some unique data (like a database ID) then this is a perfect candidate for toString() so it could return
#294: John Doe
. But uniqueness isn't a requirement.Really... Even if Mister Bloch says so... I don't think it makes sense to have any rules for implementing toString(). It makes sense for hashCode() and equals() but not for toString().
Point # 3 is the weak link in this argument, and I in fact violently disagree with it. Your invariant is (reordered)
I would say, rather:
That is, logical implication. If x and y are equal, their toString()s should be equal, but an equal toString() does not necessarily mean that the objects are equal (think of the
equals()
:hashCode()
relationship; equal objects must have the same hash code, but same hash code can not be taken to mean the objects are equal).Fundamentally,
toString()
doesn't really have any 'meaning' in a programmatic sense, and I think you're trying to imbue it with one.toString()
is most useful as a tool for logging etc; you ask how useful an overriddentoString()
would be given:I would say it's massively useful. Say you notice a lot of errors in your logs and see:
what do you do? You have no idea at all what's going on. If you see:
then you actually have some chance of working out what's going on ('Hey, someone is trying to make the Smith family marry themselves') and that may actually help with debugging etc. Java object IDs give you no information at all.
Yes it's worth it. ToString helps give tangible, visual output to the state of the object. IMO, it's especially important in an entity, because ORMs or other third party libraries print an object as a part of their logging strategy quite frequently.
will obviously implicitly call toString().
It has helped me time and time again to visually see the state of the entity to determine whether or not it's transient or persistent in the logging in terms of transactionality, and just general debugging.
Would you rather see this:
or this:
In short, the only reason you wouldn't override toString is laziness. In recent releases, Eclipse even has a toString generator!
What makes you think the goal of
toString()
is simply to have a unique String? That's not its purpose. Its purpose is to give you context about the instance, and simply a classname and hashcode don't give you context.Edit
Just want to say that I by no means think you need to override
toString()
on every object. Valueless objects (like a concrete implementation of a listener or a strategy) need not overridetoString()
since every single instance is indistinguishable from any other, meaning the class name is sufficient.Having a
toString()
method in entity classes can be tremendously helpful for debugging purposes. From a practical standpoint, using IDE templates or something like the Project Lombok@ToString
annotation simplifies this a lot and makes it easy to implement quickly.