Wednesday, December 30, 2009

Hibernate3 Tip#3: Methods You Should Override

Just some general best practices that have saved me considerable development time as I've worked with Hibernate3:
  • Always override equals(). Objects that are equal as plain Java objects are often not equal in Hibernate3 because of the identity problem. Hibernate considers the object's persistent state, database identity, and other factors to determine if two objects are equal. By overriding equals(), you set a standard of equality both Hibernate and Java can use.
  • It is a bad idea to override equals() in subclasses. Hibernate does not behave well.
  • Always override hashCode() and provide your own implementation based on the class's attributes that are expected to change rarely. I use the class identifier commonly. Actually, overriding equals() almost always requires overriding hashCode().
  • When you implement equals() and hashCode(), always use property accessors - getXX()/setXX(), POJO style. Hibernate allows the use of proxy classes or references that may no contain actual data if you call their properties directly. Believe me, this is a pain to debug!
  • Always make classes Comparable in case objects of the class end up in collections that require this feature (such as SortedSet or other collections that use a class-dependent Comparator). This gives you the flexibility to switch collection types whenever (e.g. from List to Set) without further base code changes.
  • I also always override toString() because I hate seeing memory addresses as representations of objects. I use it for debug information that I can print out and understand, and that uniquely identifies the object for me.
Pretty much every OOP project I've worked on, these are some of the first tasks that get done. If developers would just get in the habit of these best practices, I wouldn't dread inheriting their projects so much.