Skip to content
Advertisement

Are API calls in a mapper considered a bad practice?

It’s quite common to use DTOs as API models. Often you need to map those DTOs to other models afterwards. I will keep it really simple with following example:

class RequestDto {
  private String companyId;
  // more fields ..
  // getter, setter etc..
}

class SomeModel {
  private Company company;
  // more fields ..
  // getter, setter etc..
}

So in the above case RequestDto is the model that is used in the API and SomeModel is the model that is used internally by the server for the business logic. Usually you would create a class to map from one to another object, e.g:

class RequestMapper {
  public SomeModel mapRequestToSomeModel(RequestDto request){
    Company company = fetchCompanyFromApi(request.getCompanyId()); // makes a request to another service
    
    SomeModel someModel = new SomeModel();
    someModel.setCompany(company);
    // map more fields..

    return someModel;
  }
}

Question

Is it a good practice to put external API call logic (like fetchCompanyFromApi) inside such mapper functions? Are there better alternatives? (I like to keep mappers very very simple, but maybe that’s just me)

Advertisement

Answer

It seems a little smelly to me. My (personal) expecption for a mapper, particularly if other mappers are trivial, is to be very very cheap. No database or API calls involved. I would prefer so create some kind of conversion service, which performs the same steps, but is called differently.

A similar question often arises for functions that are called get… where I would never expect expensive operations.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement