Should an entity class always have an ID field
I asked "Is it really worth implementing toString()
for entity classes?". The answer I accepted demonstrated the utility of the toString()
开发者_如何学运维method of an entity class writing the "name" or "ID" of the entity (and, I'd say, not much else). But that requires that the entity have a "name" or "ID".
So, should an entity class always have an ID field. If it does not naturally have one, should you add one, given that it is useful only for debugging? A private final long
, perhaps? That can be done elegantly and efficiently.
I'm not talking necessarily about database backed classes. Here by an entity I mean a class that has the invariant (for non-null x)
x.equals(y) == (x == y)
An ID almost invariantly refers to a field that uniquely identifies a persistent record, regardless of whatever else has changed between instances of objects hydrated from that persistent record.
So, the short answer to your question is, no, a "domain" class does not necessarily have to have an ID field. Most will, as you will almost certainly want to persist your domain, and in that case it is best practice (beats the pants off a compound PK of, say, first name, last name, DOB and SSN), but if you write a class that just holds stuff in memory, perhaps a view helper or a business logic class, don't bother.
精彩评论