Code Design : microservice – Services Losing Single responsibility Principle

microservicessingle-responsibility

I am trying to implement Microservice to understand the architecture and how communication works. Many articles state that Services should follow the Single Reponsibility Principle, but it's kinda hard to achieve. For example, I have to search Item and get all the information (including stock).

So I have two services:

  • An Item Service which deals with everything related to Item. It has sub-services like ItemSearchService, ItemCreationService, etc.
  • A Stock Service whose job is to update stock, get Stock information, etc.

Is it alright if I do:

  • A rest call to ItemSearchService.searchById()
    • This will get the information (not including stock information)
  • A rest call to StockService.getStockCount()
    • This will get stock information
    • Control is returned back to ItemSearchService, where the Stock Service information is aggregated, and search result is returned

My concern: Is it breaking the Single Responsibility Principle? Because search responsibility is just to search, and here it's getting the stock information also.

Best Answer

The Single Responsibility Principle is widely misunderstood. It does not state that an object or service should "only do one thing". Rather, it states it should only have one "reason to change", where "reason to change" means business decision or technical issue which which would force you to change the code, or in this case, change the interface of the service.

So if you had a service called numberOfAvailableBlueCapsAtNewJerseyWarehouse() they you would break the SRP because this method would have to change if either the product item changes (e.g the caps are no longer available in blue) or the New Jersey warehouse is decommissioned. Therefore frequently changing factors like products and warehouses would be configured in data rather than hardcoded in a service interface.

Related Topic