Search code examples
javaspringjavabeansclean-architecture

In service oriented architecture, Is it a good practise that a mapper calls a service?


I would like to know whether it is a good practise to call/inject a (micro) service inside a custom object mapper.

This mapper transform an Entity to a DTO. In this DTO there is a field that contains a sum up of some values (need some business logic). I defined a service to centralice the logic as it is used in many other places.


Solution

  • Although there is strictly speaking nothing incorrect about calling a service from a mapper, it does add dependencies to the mapper, which is usually a pure object (Plain Old Java Object, POJO) that simply converts an object of one type to another. An alternative is to pass the required information into the mapper as a parameter. For example, suppose your current design resembles the following:

    public class Foo { /* ... */}
    public class FooDto { /* ... */}
    
    public class FooService {
    
        public FooResults getSomeResults() { /* ... */ }
    }
    
    public class FooMapper {
    
        private final FooService service;
    
        public FooMapper(FooService service) {
            this.service = service;
        }
    
        public FooDto convert(Foo foo) { 
    
            FooResults results = service.getSomeResults();
    
            // ... use results ...
        }
    }
    

    Instead of having the FooMapper dependent on the FooService, you can pass the FooResults in as a parameter to the convert method:

    public class FooMapper {
    
        public FooDto convert(Foo foo, FooResults results) {    
            // ... use results ...
        }
    }
    

    The advantage to this approach is that FooMapper is no longer dependent on FooService. Instead, the client that calls the convert method must have a reference to the FooService to obtain a FooResults object.