Great question! First define encapsulation and from there. This wikipedia article defines encapsulation as follows:
- A language mechanism for restricting access to certain components of an object.
- A language construct that facilitates combining data using methods (or other functions) that work with this data.
Serialization, at least as Java does, has implications for both of these concepts. When you implement the Serializable interface in Java, you are essentially telling the JVM that all your member variables are not transient and the order in which they are declared defines a contract by which objects can be recovered from the byte stream. This works recursively if and only if all of your member variable class definitions also implement Serializable , and this is where you may run into difficulties.
Encapsulation problem
Based on the previous definition of encapsulation, especially in the first element, encapsulation does not let you know anything about how the object you are working with really works under the hood in relation to its member variables. Implementing Serializable “correctly” makes you, as a developer, learn more about the objects you deal with than you probably care about in a functional sense. In this sense, the implementation of Serializable directly contradicts encapsulation.
Custom serialization
In each case, serialization requires knowledge of which data is an “object” of a particular type. The Java Serializable interface does this to the extreme, forcing you to know the transient state of each member variable of each Object that you want to serialize. You can get around this by defining a serialization mechanism external to the types that should be serialized, but there will be trade-offs between projects - for example, you may have to deal with objects at the level of the interface (s) that they implement, instead of direct interactions with their member variables, and you may lose some ability to restore the exact type of an object from a serialized byte stream.
source share