Facade design pattern over data types

31 Views Asked by At

I have a class named MyClass in subsystem A, and a method in subsystem B has arguments of type MyClass. My subsystems are highly coupled, so I want to make a Facade for subsystem A. Should I somehow pass the MyClass type trough the Facade? What is the right way?

thanks

2

There are 2 best solutions below

2
Augusto On BEST ANSWER

It depends (tm), but it's usually a good idea to have separate classes that are used by an API and classes that are internal to the system. If for whatever reason MyClass needs to change in System A, you probably don't want that change to cascade and impact System B.

In your example, if each subsystem should be as loosely coupled as possible, one approach would be to have an adapter that is external to both subsystems, but it's able to adapt the calls from one to the other.

Just a word of caution, overusing design patterns is not a good idea. I think in your example it's worth asking oneself if the subsystems should be separate or if they are one.

0
Mark Seemann On

If I understand the scenario correctly, you have this direction of coupling:

B -> MyClass

where the arrow indicates the direction of dependence.

If you make a Facade for subsystem A, the dependencies will now look like this:

B -> Facade -> MyClass

Thus, B will still depend transitively on MyClass.

If you want to decouple subsystem B from subsystem A, consider the Dependency Inversion Principle:

  • High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
  • Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.

Thus, let subsystem B define the abstraction that it needs, and then let the detail implement the abstraction. It may look like this:

B -> Interface <- MyClass

If you put the interface in subsystem B, you've now reversed the direction of dependence, but you can also put the interface in a separate subsystem so that both A and B depend on the abstraction, but not on each other.