0

I'm developing an API with ASP.NET, but I'm having some questions about the best way I should develop the controller layer for the products.

I'm having these questions because each product will have its own service and its own purchase path, so product1 might have a step 1, step 2 and step 3 to buy and product2 might have another step 1, another step 2 and so on.

But I think it's not interesting that my frontend has an:

if(Productid = 1) {
    post("http://url/product1")
} else {
    post("http://url/product2")
}

I believe it would be better if my frontend just make a post("http://url/product") call and on the backend side I forward the data to the correct service.

I would like to know if there is a cleaner and more sustainable way to develop my API structure and that for each new product I don't need to add one more if(Productid==3) to direct to the correct route in the frontend but I still don't have the knowledge of how to best structure this.

1
  • 1
    Why not post("http://url/product/{Productid}")? Commented Jun 26, 2021 at 18:02

1 Answer 1

0

It's a good design decision to expose a unified interface to your clients.

At the server side, you can use strategy pattern to dispatch an incoming request to the right processing procedure.

Another pattern worth to have a look is Visitor pattern which is quite useful on routing requests to a right handler behind an unified interface.

Or you can also create a service factory to produce the right purchasing service for a specific product then use the service to complete the processing.

No matter which pattern you use, there are two principals you should follow:

  1. Use a separate domain service to encapsulate product purchasing business logic. Turn the Controller into a simple middle-man who is only responsible to deserialize the Request into COJO bean then pass it to domain service. This design will decouple your business logic from Controller layer (tightly coupled into HTTP communication, serialize/deserialize). Your code will become testable.

  2. Use Interface to define the generic product purchasing Service contract to be used by the Controller. Create concrete service implementions for different product types. It will make your module easy to extend when you want to add new processing procedure for a new product type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.