Tuesday 30 July 2024

Facade Pattern

The Facade pattern is a design pattern that provides a simplified, unified interface to a set of interfaces in a subsystem, making it easier to use. It hides the complexities of the subsystem by providing a single point of access, thus reducing dependencies and making the subsystem easier to work with.

If you follow the Single Responsibility Principle and create a vast network of decoupled classes all of which focus on their own specific responsibility, you can very quickly create a rather complex ecosystem of loosely coupled classes, which can prove to be extremely beneficial from the code maintenance perspective. It's much easier to maintain and upgrade a lot of small focused classes, than it is to try and work with one giant monolith of spaghetti code; however this decoupled ecosystem may prove to be more difficult to work with for consumers of the functionality. 

The facade pattern aims to alleviate this complexity by providing a unified interface to a set of interfaces in a subsystem. The facade defines a higher-level interface that makes the subsystem easier to work with.

When should you use the Facade pattern?

  • When you want to provide a simple interface to a complex subsystem. Most patterns, when applied, result in many small domain specific classes. This makes the subsystem more reusable and customisable, but it also becomes harder to use for clients that don't need to customize it. A facade can provide a simple default view of the subsystem that is good enough for most clients
  • There are many dependencies between clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.
  • Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades.
The Facade pattern is generally implemented for the sake of the Subsystem consumers, not so much the creators, though by simplifying the use of the subsystem this benefits the creators by limiting the amount of questions the consumers will have to make.