How to separate object to DTO and BO?

127 views Asked by At

I have an old object that contains data and behaviour. This object is serialized by JSON to be stored in a file and transmitted between users.

Now I want to separate object to data transfer object and business object, because I need to serialize only data, without behaviour. But I have issue with deserializing of old object.

How I can correctly to do this separation?

Thx!

UPDATED: So I had a Class1 with data and behaviour. I created a Class1DTO and moved to it data from Class1. In Class1 I store behaviour only.

I want to serialize and deserialize Class1DTO, but in older file I have serialized Class1 (with data and behaviour). This is my issue - I cant deserialize old files, because in new version of my prorgam I store in file Class1DTO, not Class1.

So I want to change serialized object

1

There are 1 answers

0
antonzy On

I would advise to create a complete separation between Class1 and Class1DTO.

I'm assuming your Class1 represents a business Model (consisting of state and behaviour). Therefore, it is completely ok to have duplicate properties (data) in both Class1 and Class1DTO, because each of one them suits a different purpose. The best option would be using Class1 for your business logic (and holding data), while using Class1DTO to only represent the data transferred over the wire (outside the application boundaries).

By creating a matching DTOMapper that translates between Class1 and Class1DTO (back and forth) you can easily solve your serialisation/deserialisation problem.

public class Class1DTOMapper{
    public Class1DTO map(Class1 x){
       return new Class1DTO(...);
    }

    public Class1 mapBack(Class1DTO x){
       return new Class1(...);
    }
}