0

Lets say we have a layered architecture where A->B->C are three different layers. Function calls are passed from A to C and data is passed up from C to A.

I think in this case A will have a reference to B and B will have a reference to C. These classes are tightly coupled. How should they call each other while keeping them as independent as possible?

New contributor
stacktenay is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • HI. Your question is waaay to general, I don't think it can be addressed properly within a single answer here, so, IMO, it would be better if you could find a way to break this down into a series of more specific questions. – Filip Milovanović Feb 13 at 10:47
  • In any case, decoupling more or less boils down to (1) coming up with a stable abstraction (something that captures the interaction between the components, like an interface, an abstract class, a data structure, a convention of some sort) - something that's expressive enough to let you write the code in terms of it, but can remain relatively unchanged while the components themselves change, and (2) the dependency inversion principle (which is basically about how to make one component be like a "plugin" to the other). So maybe a good way to find more concrete questions is to study those. – Filip Milovanović Feb 13 at 10:50
  • Question is too broad, you'd have to write a whole book on OO and software architecture. Coupling is not always bad, what is the real problem you are trying to solve? – Martin K Feb 13 at 21:26
1

There are two main techniques that can help you:

  1. Program to interfaces. For each class, at each level, create an interface (or abstract class, depending on the language you're using). The interface defines any methods, and any other public features. The concrete classes inherit from the interfaces. You can decouple the layer above from the one below by specifying only the interface it uses, not the concrete class. Concrete classes can be swapped in and out as desired.
  2. Dependency injection. Rather than each class creating the objects of the classes below, use a dependency injection framework to push them in from the "top". Now, not only do the objects on each layer not need to know exactly which classes they are using, but they don't need to create the objects from those classes, either.

But don't get too carried away. Keep in mind the KISS (Keep It Simple, Stupid) and YAGNI (You Ain't Gonna Need It) principles. Simple code is easier to maintain in future. Only add extra layers of indirection if it helps the design and testing of your code.

Your Answer

stacktenay is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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