views:

171

answers:

2

Currently, we serialize user's session object into database but the object changed too much lately so we decide to redesign this process. We all agree that we can't serialize the whole object and we need to save it field by field. There are 2 proposals,

  1. Store all fields in a map and serialize the map.
  2. Use ObjectOutputStream.putFields().

We don't see much difference between these 2 approaches. The #1 uses familiar map interface and it's easier for everyone to use. The #2 provides the convenient methods like fields.get("confirmed", false) etc.

We tend to go with #1. Anyone know any other benefits of #2?

A: 

According to this site, you can customize how the values are read and written by implement two private methods named writeObject(ObjectOutputStream) and readObject(ObjectInputStream) in your class. Check the session "Customize the default protocol" on the site above. This is probably the preferred method and, if I remember correctly, is also the recommended way described in the Effective Java book.

By doing it that way, you maintain the logic of what fields should be read/ written in the class that contains the fields, which is better encapsulation.

Ravi Wallau
+1  A: 

readFields and putFields have the advantage that you can start off using the default serialisation, and only add the boilerplate when you need it.

A Map will produce smaller streams if used once, but a stream that stores lots of these object will be smaller if it uses readFields/putFields. This is because there is a one time overhead describing the format of the stream.

Note you should always call defaultReadObject/readFields at the start of readObject and defaultWriteObject/putFields at the start of writeObject. Unfortunately this is not checked.

Tom Hawtin - tackline