A Value Object Base Class
Value Objects (aka Data Objects) are pretty common. They typically have little or no functionality, but rather just contain one or more data fields. They’re used to represent database entities, to represent model objects in MVC applications, etc.
To be well-behaved members of Collection
s they should have good hashCode()
and equals()
methods, and for debugging should have good toString()
methods. To be stored in a Session
, they must be serializable. So I’ve developed a simple abstract base class that meets these requirements.
It uses Jakarta Commons Lang utility classes for default reflection-based implementations of
hashCode()
, equals()
, and toString()
, it implements Serializable
, and has a Logger
1 in case concrete subclasses need it. The logger is transient
because it isn’t serializable, and also shouldn’t be included in hashCode()
, equals()
, and toString()
(Commons Lang ignores transient
s by default).
Of course any concrete subclass can override any of the three methods if the default implementation isn’t sufficient. But I find that’s the exception rather than the norm.
The code:
package com.foo.bar.model; import java.io.Serializable; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.log4j.Logger; /** * Abstract base class for value objects. Contains reflection-based default * methods for hashCode, equals, and toString. * * @author Burt */ public abstract class DataObject implements Serializable { protected transient final Logger _log = Logger.getLogger(getClass()); @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(final Object other) { return EqualsBuilder.reflectionEquals(this, other); } }
- I gave up on Commons Logging a while ago since I always use Log4j[back]