Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facade design pattern and close coupling

When learning Facade design pattern, everywhere I find this kind of examples:

public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}

I don't know if I'm wrong but doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.

like image 242
Grizabela Avatar asked Jul 09 '26 23:07

Grizabela


1 Answers

In a way you wrote your example, yes it will tightly couple your code. Mainly due to new keyword which acts like a glue to your dependencies.

Keep in mind that Facade pattern will not prevent you from creating tightly coupled dependencies or code. Main purpose of using it is to make your software component easier to use, more readable and maintainable and last but not least more testable.

If you want to avoid tightly coupling, you need to pass abstract dependencies in your Facade class:

public class Facade
{
 private readonly ISystemA subsystemA;
 private readonly ISystemB subsystemB;

 public Facade(ISystemA subsystemA, ISystemB subsystemB)
 {
    this.subsystemA = subsystemA;
    this.subsystemB = subsystemB;
 }

 public void CreateAccount()
 {      
   this.subsystemA.CreateCreditCard();
   this.subsystemB.CheckCreditCard();
 }
}

You need to create interfaces (or abstract classes):

public interface ISystemA
{
 void CreateCreditCard();
 //other methods here
}

public interface ISystemB
{
  void CheckCreditCard();
  //other methods here
}

In that way you ensured that your Facade does not depend upon implementation, rather it depends upon abstraction. You'll be able to pass any implementation which implements ISystemA or ISystemB intefaces.

I suggest you to read more about Dependency Injection and containers which will greatly help you to wrap up classes' dependency graphs and automate constructor injection in that classes.

like image 56
Darjan Bogdan Avatar answered Jul 13 '26 16:07

Darjan Bogdan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!