I am trying to follow clean architecture in my software. I have implemented 3 layers: data layer, business layer and presentation layer.
As far as I understand dependency will follow outside to inside like P->B->D.
But my question is should I do a singleton data layer executor injection into presentation? Doesn't that break this logic?
Or without DI, only create an abstraction between layers I think creates tight coupling.
So referring to some data layer dependency from inside the business layer - doesn't that make the layers tightly coupled?
public class ViewModel<T> extends GenericRouter {
IPresentation ip = new BusinessUseCaseImpl();
public abstract class BusinessUseCase<T extends HashMap> implements IPresentation<T> {
UserRepository urepo = new UserRepository();
2 Answers 2
In the clean architecture, the inner layers are logic, not infrastructure.
When the business layer instantiates the data layer, it injects any infrastructure dependencies that it requires.
Similarly, when the presentation layer instantiates the business layer, it passes in any infrastructure dependencies that it requires. This is how the business layer gets the infrastructure it needs to pass to the data layer.
And initially, when the application/system instantiates the presentation layer, it passes in the infrastructure that it will need. The humble object pattern should be used to implement these dependencies, because they are the only part of the system that can't be tested independently from infrastructure.
Comments
It depends on what you mean by "tight coupling". Following the 3 layered architecture is ok for the data layer to be a dependency on the business layer and the business layer to be a dependency on the presentation layer.
Instead of injecting a concrete class, you can always define the dependency injection on an Interface. With this, you can always switch the implementation as long as you follow the agreed interface.
However, my experience tells me that you rarely or never do this for a basic and regular 3 layered architecture. You have always a single Service and a single Repository/DAO implementation so having an Interface for each of them is kind of redundant and useless.
I think that the most important thing when you work with 3 layered architecture is to never bypass layers. Examples:
- You should never make the presentation layer depend directly on the data layer. Always go through the business layer.
- The relation between the layers should be always 1:1. This means you should never make a Controller call a Service that is associated with another Controller.
Not following these rules will for sure make your code incredibly hard to read and understand. Of course, for every rule, there is an exception, but try to stick to them.
6 Comments
Explore related questions
See similar questions with these tags.