Friday, December 26, 2008

serialVersionUID best practice?

What is the best practice when in comes to serialVersionUID for data transfer objects? Specifically, objects sent over RMI.

There are 3 options:
  1. Let the JVM generate the value.
  2. Set the serialVersionUID to a generated value (ie let eclipse generate a value for you).
  3. Set serialVersionUID to a specific value.

Option one will guarantee you won't have backwards compatibility. Most people will say that is a bad thing, but to me making a decision to not deal with class level backwards compatibility, and enforcing it by not defining serialVersionUID, is a valid architectural choice. However, if it turns out you do need it, you may find yourself in a fix. There are other gatchas too: caches storing objects to disk, clustering implementations passing objects between servers, and web servers persisting session objects to disk are a few. In these cases you may need to maintain compatibility.

The second option will give you incidental backwards compatibility. I say incidental because it doesn't make the class compatible automatically. It only tells the JVM that it is compatible. Actual compatibility takes a lot more work.

Relying on a generated value means you are also relaying on your fellow developers to understand what constitutes a incompatible change and remembering to regenerate the serialVersionUID when they make one. The former depends on what shop you work at, the later i would never depend on. This means you will have to either deploy common classes to both client and server every time anyways, or make sure you do careful testing.

The third option may seem similar to the second, but it has the added benefit of allowing you to set the serialVersionUID to a specific value (lets say 0). You can use this to declare there has not been any attempt to make the class backwards compatible.

For those classes that need to be compatible, it also allows you to set the value to the version of the class (start at 1 and increment for each incompatible class change).

What do you think? Which option is the best? Is there any other that i'm over looking? Have a look at http://java.dzone.com/articles/dont-ignore-serialversionuid, then rate my post +1 brilliant or +1 stupid.



Blog Directory Listing