Call a service method from another service class
I have two service classes. WarehouseManagementService provides methods for managing warehouses and inventory. SalesManagementService provides a way to manage customers and their orders.
To create an order, you must check that the order quantity is sufficient. To do this, I’ll use the method availableStock(Product p) in WarehouseManagementService. But I don’t know how to call this method properly.
Do I have to create an instance of WarehouseManagementService in SalesManagementService? Or should I add the WarehouseManagementServiceInterface to the SalesManagementService constructor (dependency injection)?
To achieve loose coupling of these two classes, what should a good architecture look like?
Thanks in advance.
public class WarehouseManagementService implements WarehouseManagementServiceInterface {
private DatabaseReadWarehouseInterface dbRead;
private DatabaseWriteWarehouseInterface dbWrite;
public int availableStock(Product p) {
returns available quantity of product
}
}
public class SalesManagementService implements SalesManagementServiceInterface {
private DatabaseReadSalesInterface dbRead;
private DatabaseWriteSalesInterface dbWrite;
public void addOrder(Order o) {
creates order, if product quantity is sufficient
}
}
Solution
You have the right feeling: dependencies should be injected. Remember Single Responsibility Principle: “A class should have only one reason to change”.
By constructing WarehouseManagementService in SalesManagementService, you can add a second reason to change SalesManagementService
: when constructing your
The way when WarehouseManagementService
changes.
To work around it, you can use a full-fledged dependency injection framework, or simply start by adding constructor parameters to SalesManagementService
:
public class SalesManagementService implements SalesManagementServiceInterface {
private DatabaseReadSalesInterface dbRead;
private DatabaseWriteSalesInterface dbWrite;
private WarehouseManagementServiceInterface warehouseManagementService;
constructor(DatabaseReadSalesInterface dbRead,
DatabaseWriteSalesInterface dbWrite,
WarehouseManagementServiceInterface warehouseManagementService) {
this.dbRead = dbRead;
this.dbWrite = dbWrite;
this.warehouseManagementService = warehouseManagementService;
}
public void addOrder(Order o) {
creates order, if product quantity is sufficient
}
}
Then in your main
method, notice to instantiate the WarehouseManagementService and pass it to the SalesManagementService
.
As a side note, you may want to move the construction of SalesManagementService and WarehouseManagementService
to the factory that provides you with the SalesManagementServiceInterface
and
> WarehouseManagementServiceInterface
instead of a concrete class (“program interface, not implementation”).