Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should serialization logic be in the entity or other class

Where should object serialization logic (the mapping of fields into XML or JSON names and values) be placed? Inside each entity object OR into a different set of classes only concerned with serialization? Any other best practices out there that relate to this question?

For example:

class Person {
    String name;
}

Some people go about it this way:

class Person {
    String name;
    public String toJson () {
      // build JSON, use 'name' field
    }
}

But if we also needed toXML(), toCSV(), toXYZ() keeping that direction would create horribly polluted code and break the Single Responsibility Principle which is already broken even with a single toJson method, IMHO.

Another option and this is what I typically do:

interface Serializer {  public String toJson (); }

class PersonJsonSerializer implements Serializer {
    private Person p;
    public PersonJsonSerializer (Person p) { this.person = p; }
    public String toJson () {
      // build JSON, use p.name
    }
}

then a factory hands out Serializers depending on entity types:

class JsonSerializerFactory {
    public Serializer getSerializer (Object o) {
        if (o instanceof Person) {
            return new PersonJsonSerializer ((Person)o);
        }
        else if (o instanceof Account) {
            return new AccountJsonSerializer ((Account)o);
        }
        // ... etc
    }
}

There would also be XMLSerializerFactory, CSVSerializerFactory, and so forth.

However, most of the times people want to have full control over the serialization and would not buy into it and prefer to have toJson methods inside each class. They would claim is way simpler and less error prone.

What is the preferred way to go, and are there better alternatives to implement a solution to this problem?

like image 253
Jose Cifuentes Avatar asked Sep 25 '22 06:09

Jose Cifuentes


People also ask

What are the conditions necessary for a class to be serializable?

Each superclass that is not serializable must have a public default constructor - a constructor with no parameters. Your class must implement the Serializable interface. Your class must serialize and deserialize the not-serializable fields in the superclasses. Transient data type is not serializable.

Are classes serializable by default?

It's a little bit philosophical but by convention the default type of a class is not serializable, unless you explicitely define "this class can be serialized".

When should we implement serializable in Java?

Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class. Serializable classes are useful when you want to persist instances of them or send them over a wire.

Where do we use serialization in Java?

Serialization in Java is the concept of representing an object's state as a byte stream. The byte stream has all the information about the object. Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport the code from one JVM to another and then de-serialize it there.


1 Answers

I would say the serialization logic should not be part of the POCO/data classes for many reasons:

  1. Single Responsibility Principle (data classes should only define data model, note serialization logic)
  2. There could be different kinds of serializers that you may require (json/xml etc. as you mentioned)
  3. Serialization implementation most of the time is a generic solution or an external package. Even if you want custom implementation for some objects, still you can have a generic solution which you can extend for specific classes, so no need to have it for each class.
  4. You can decorate your POCO classes with attributes to direct the serializer for special conditions (like to control sequence of properties, property names or even a customer serializer for complex type properties)

There will be other reasons as well but there are some strong arguments why you should not put the serialization logic into your POCO/Data Model.

like image 97
Naeem Avatar answered Sep 28 '22 05:09

Naeem