I want to ask about Architectural pattern. I write two snippet code to demo what I ask.
The first way is:
//a method on controller layer (in Spring framework)
@RequestMapping(...)
public ShopDTO findShop(final Long shopId) {
Shop shop = shopService.getShopById(shopId);
ShopDTO shopDTO = shopMapper.toShopDTO(shop);
return shopDTO;
}
//A method on service layer
@Transactional
public Shop getShopById(final Long shopId) {
//some code to find an entity by id
}
ShopDTO in controller layer.The second way is:
//a method on controller layer (in Spring framework)
@RequestMapping(...)
public ShopDTO findShop(final Long shopId) {
ShopDTO shopDTO = shopService.getShopById(shopId);
return shopDTO;
}
//A method on service layer
@Transactional
public ShopDTO getShopById(final Long shopId) {
Shop shop = shopRepository.findById(shopId);
ShopDTO shopDTO = shopMapper.toShopDTO(shop);
return shopDTO;
}
ShopDTO in service layer.I use Spring framework code for example.
My question is: Which is the best layer to place mapper code. And can you tell me why?
By the way, what type logic should place on controller layer and what should place on service layer?.
The second way is better.
The reason is, that you want to have certain abstraction between your layers. The controller should just get the shop by its id. That way, you can change how you map and retrieve data without having to change the controller. Then you should go to the next step and think how to best design the abstraction on the boundaries of your data access layer and the service layer.
About what logic to have in the controller. In the controller you should place logic related to the incoming request and the final response of your API. Maybe you can do some validation (althought most is better to be performed via interceptors), extract header values and do things with them and have your final exception handling clause so that nothing spills outside your API unexpectedly and you can reply with the proper HTTP 5xx response. In general the controller should not have large methods, they are primary there to expose your API endpoints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With