Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not make a class Serializable?

I'm storing some objects in my viewstate and I was wondering if there are any disadvantages to making a class Serializable?

Is it bad practice to make all of the classes Serializable?

like image 808
Brad8118 Avatar asked Mar 28 '11 21:03

Brad8118


2 Answers

Firstly. Avoid viewstate.

Generally serialization (textual) is used for transferring objects.

You should avoid marking any class as serializable that is not a DTO (Data transfer object) or message class. We do this for several reasons. What ever picks up your class in serialized format may not have the method information (which is in the original assembly) of a non DTO class. Secondly, a class may reference a resource (DB connection, file handle, etc) Do NOT serialize these, since de serialization does not re-establish resource connections and state, unless explicitly designed for, but is still a bad idea.

So in summary: Do NOT serialize when you have contextual methods and storing data for a thrid party to use. (Like a service response with methods is a bad idea). And do NOT serialize when the class contains a resource reference. Keep your serializable object clean from methods as much as possible. This might involve a little re factoring into a service type pattern.

Do serialize DTO's and messages.

This is more of a design choice.

like image 194
Slappy Avatar answered Nov 06 '22 09:11

Slappy


It is a good practice to make all classes that are actually Serializable as Serializable. I would just use common sense, and set it for those classes that are intended for crossing process boundaries (DTO classes).

So it those classes which:

  • All their properties are simple types
  • And if they have complex properties, their types themselves are serializable
like image 30
Aliostad Avatar answered Nov 06 '22 11:11

Aliostad