This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
We know that, if we anticipate objects are passed by value over a remote method calls, or should we choose to serialize/deserialize the objects or want to save the object as a bytes to some file (and many other usecases), we are required to have our class implement Serializable. But lately I was just curious, if any cost is associated with the implementation of this marker interface. What if, we do not have any such requirements that are needed for Serialization, but still want to make it a serializable. I understand that there is no need to do anything that is absolutely not needed, but what if decide to make it Serializable. Would this decision cause some sort of unexpected behaviour?
I avoid Serializable like the plague. It completely breaks all encapsulation. Instead, if I want to save my objects, I usually add a methods like this to my class:
Or in the case of immutable objects:
Serializable makes your class' private fields part of the specification, which is absolutely horrible.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
In that case, it would probably be a good idea to implement Externalizable. That way you get the benefits of it being Serializable (e.g. works with ObjectOutputStreams), but the class controls the read/write.