I’ve been trying to clean up the serialization story in Jaxen lately. Bottom line is that you really shouldn’t just willy-nilly declare that classes and interfaces implement
Serializable. Getting serialization right is not hard, but it is tedious; and it needs to be thought about and tested. There’s a lot more to it than just adding
implements Serializable to every class.
After I filed one bug, the usually reliable Brian Ewins made the comment that, “I also thought it was considered best practice not to declare interfaces serializable.” That sounds plausible, but I can’t really figure out why; nor can I make strong case for the opposite position. So here’s the question. Given an interface
Foo is it or is it not a good idea to declare that
Serializable? (given that you do in fact want the instances to be serializable, of course.) Or should one leave
implements Serializable off the interface and just place it on the concrete classes? Why or why not?
A slightly less boolean variant of this question: when should one mark the interfaces
Serializable and when should one mark the implementation classes
The only reason I can come up with is that since most of the work of making a class serializable (calculating a
serialVersionUID, providing custom
writeObject() methods, marking fields
transient, etc.) you don’t want to declare that something
implements Serializable until you know that work has been done. If the interface declares that it
implements Serializable, then the implementations are likely to happen by accident, and the necessary work won’t get done. This leads to fragile, brittle, and broken serialized forms. That makes sense, but it doesn’t feel like a very string argument. Can anyone suggest a better reason why one should or should not declare an interface
Serializable? Comments are open.