Let's assume I have an API endpoint which needs some Product data to process the requests properly. Imagine that there's some application layer service which has to handle the contract (let it be a query for example). The application layer service communicates with some external provider in order to get the Product information. Pseudocode could like this:
class ApplicationService
{
IProductCache _productCache;
IProductProvider _productProvider;
public void Handle(Contract contract)
{
var products = _productCache.GetProducts();
if (products == null)
{
products = _productProvider.GetProducts();
}
...
}
}
In such a solution application layer is aware that there's some caching mechanism and the application service firstly communicates with cache then with the provider. We could also encapsulate the caching mechanism in the infrastructure layer (in which IProductProvider implementation belongs to). We would have something like this:
class ApplicationService
{
IProductProvider _productProvider;
public void Handle(Contract contract)
{
var products = _productProvider.GetProducts();
...
}
}
class ProductsProvider : IProductProvider
{
IProductCache _productCache;
public Product[] GetProducts()
{
var cachedProducts = _productCache.GetProducts();
if (cachedProducts not empty)
{
return cachedProducts;
}
// else communicate with external provider
...
}
}
Which solution is better and more proper? What are the advantages and disadvantages of both of them? Could you share your thoughts on this? Thanks in advance for any help.