Search code examples
javaservicemoduledependencies

Two Modules and one service. How to handle?


Situation:
Module A; Module B; service;

Module A needs service.getSomething()
Module B needs service.getSomethingSimilar()

There are some variants of implementation. Some of them are:


=1=
Implement a service in Module A and in it make the method getSomething
Implement a service in Module B and in it make the method getSomethingSimilar

Pros:
You don't get module interdependency

Cons:
Because the two methods are very similar, you are basically duplicating code.


=2=
Implement a service with the two methods in Module A and use that service in Module B.

Pros:
No code duplication
Both methods are in the same service

Cons:
Module interdependency


So what is the best approach for this situation?


Solution

  • I think you can use strategy design pattern for this problem

    Have a service interface getSomething() and then make a service implementation getSomethingImpl()

    Both Modules A and B will provide their own implementations for getSomething interface tuned into them, For now you can set the getSomethingImpl as the desired implementation for two modules and if needed you can create new implementations later on

    This approach combines the benefits of both as it reduces redundancy and reduces the coupling i.e interdependence of 2 on each other

    Possible con is though code is easier to maintain now it would require some extra classes and code for this implementation

    Refer:https://en.wikipedia.org/wiki/Strategy_pattern