spring-bootdesign-patternssolid-principles

Managing controllers for identical entity structures?


I am developing a Spring Boot app and I am faced with the following situation:

I have x and y entities, but the fields of these entities are exactly the same, and because of this they both use the same DTO (the only difference is that they have different names and both have their own database tables). This situation results that I currently have two identical controllers.

For business reasons, they have to be two separate entities, even though they are the same fields.

What is the correct procedure in this case?

Even though it is code duplication, do I keep both controllers so that one controller can be responsible for only one entity?

Or can I somehow make it so that I can use one controller for both entities, with a dynamic path, and by highlighting the entity type in the path, I can differentiate which service implementation it uses (because the service interface is the same, the two implementations differ in a few details, and one goes to table x and the other to the table y)?


Solution

  • If they are two separate business entities, then it's better to have two separate controllers. For example, the first one could have a request mapping /customers, and the second one could be /companies. You can create some generic DTO class given that the two entities share common fields.

    Also, you can go with one controller method and declare a path variable for the entity type (/api/{entityType}, for example if you're dealing with customers, then the entityType's value would be "customers", etc.) . Upon receiving a request, you would check the entity's type and delegate to an appropriate service class that encapsulates the business logic related to the called entity.