Search code examples
javaobjectdesign-patternspojo

Adapter class vs toXXX() method in data class


I have a scenario where I want to convert an object to a service request object type to call a service.

I have a data object like this:

class Data {
  int val;
  ...
}

I want to convert this object into a service request object lets say DataRequest. I'm thinking of these two options:

1. Have a toDataRequest() method in the Data class itself.

class Data {
  int val;
  ...

  public DataRequest toDataRequest() {
    ..
  }
}

2. Have a separate class DataAdapter, and have adapt method in it, which returns the DataRequest object.

class DataAdapter {
  public DataRequest adapt(Data data) {
    ... 
  }
}

I'm leaning towards the 1st, as it helps reducing the number of classes. I'd love to hear, what is a general recommendation for this use-case?


Solution

  • It depends on your architecture. Often you have a service layer and at least a persistence layer. The service layer is above the persistence layer and usually the architecture only allows accesses from a higher layer to a lower layer. E.g.

     +----------------------------+
     |       service layer        |  // request object is placed here
     +----------------------------+
                  | depends on
                  V
     +----------------------------+
     |    persistence layer       |  // Data object is placed here
     +----------------------------+
    

    So when your Data object has a method public DataRequest toDataRequest() it has a dependency to DataRequest and this means a lower layer has a dependency to a higher layer. This is usually not what you want.

    So if you use your DataAdapter (also known as DataMapper) and place it in the service layer you will respect the architecture shown above.

    You can also implement the mapping logic in the DataRequest.