Implementing Serializable?

When does it makes sense to implement Serializable? Should we implement it for all domain classes or only in certain cases? This is a question that has popped up repeatedly in my previous projects and I would like to answer it in this article. But first, let’s have a look at what Serializable actually does and what it is meant for without going into the details.

Serialization is the conversion of an object into a sequence of bytes. This enables to store data on disk or to transmit it across the network from one running JVM to another. Deserialization is the reverse conversion, i.e. the reconstructing objects from  a series of bytes. In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable. By implementing this interface, it marks the class to be serializable.

But why are not all java classes Serializable by default? Making a class serializable comes with certain costs:

  • Assume you implemented Serializable for a class in your application in production. Clients are working with this class version and are storing some objects to disk. After a certain time, your class is changed and released again. What happens if the customer is trying to deserialize an object of the old class version? Yes, clients will experiences program failures. Implementing Serializable restricts the future flexibility. Once you released a serializable class, you are required to support the serialized form forever.
  • Serialization can also lead to security problems. By being able to serialize any object it has a reference to, a class can access data it would not normally be able to (by parsing the resultant byte data).
  • Serialization also increases the testing burden as you must ensure the proper functioning of the application with all your class versions.

There are other issues, such as the serialized form of inner classes not being well defined. Making all classes serializable would exacerbate these problems. Although it is very easy to make a class serializable, it should be well thought out, when this should be done. In today’s business applications, mostly a web- or restful-service is used for remote communication. Thus, there is mostly no need to implement Serializable.


Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

Du kommentierst mit deinem Abmelden /  Ändern )


Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s