This newsletter represents the third segment in our design patterns series, where we've previously explored the Decorator and Adapter design patterns.
What is Facade Design Pattern ?
Facade is structural design pattern which simplifies complex systems ( classes or libraries) to simple solution using interface.
Example
Recently while working with .NET Web APIs I came up with a situation where I had multiple classes.
RolesService class with following methods :
CreateRoleAsync
UpdateRoleAsync
DeleteRoleAsync
GetRoleByIdAsync
GetRolesListAsync
Above class has 10 more methods, on similar fashion I had UserService, CurrenciesService and AccountsService with 10+ methods in each class.
I was only interested in RoleIds, CurrencyIds, AccountIds and UserIds.
So instead of creating instance for each service and calling needed methods, I created a FacadeClass named MasterService and injected services in its constructor.
Then I added an interface with 4 methods (GetRoleIds, GetAccountIds, GetCurrencyIds, GetUserIds) which I was looking.
MasterService implemented that interface IMasterService.
In my desired controller/class I only injected the Facade Interface (IMasterService) and called the methods
What did we achieve ?
By doing so, I encapsulated the complexity of the underlying services and provided a simplified interface (IMasterService) that only includes the methods I was interested in (e.g., retrieving RoleIds, CurrencyIds, AccountIds, and UserIds).
This way, your controller or class only needs to interact with the MasterService facade, making the code more manageable and modular.
Benefits of Facade ?
Following are the benefits of facade :
Provides a unified and simplified interface to a subsystem.
Promotes loose coupling, isolating clients from subsystem implementation changes.
Improves code readability by offering a clear entry point to the subsystem.
Hides internal subsystem details, promoting encapsulation.
Facilitates integrating new subsystems without impacting existing client code.
It's possible that you've employed the Facade pattern in the past without explicitly recognizing it.
Whenever you’re ready, there are 2 ways I can help you:
Promote yourself to 9700+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far at one place. Join here