In general, is it a best practice to have simple POJO Java classes implement java.io.Serializable?
views:
837answers:
4Only if you need to be able to serialise them. It's not worth the effort otherwise.
Generally not. Joshua Bloch says to implement Serializable judiciously. A summary of drawbacks that he describes:
- decreases flexibility of changing class implementation later - the serialized form is part of the class's API
- makes some bugs and security holes more likely - an attacker can access class internals within the serialized byte stream
- increases test burden - now you have to test serialization!
- burdens authors of subclasses - they have to make their subclasses Serializable too
Of course, sometimes you need a POJO to implement Serializable, say for RMI, but if the need isn't there, your code will be simpler and more secure without it.
It depends more on the needs. In the context of web applications, some web servers (eg. Tomcat 6) even make it mandatory to serialize the classes whose objects we store in sessions.
One thing I've done to address the fact that the serialized form is not backwards compatible (say when dynamically reloading a class on a running system), is load the fields I want to save into a hashmap and then serializing that. That way, I can always deserialize in the data, even if there are missing fields. You might have to provide defaults for missing keys, but it's better than messing up field order.