You may have heard recently about a topic whizzing around the Angular community: facades in NgRx. I thought it’d be a great idea to write an article to talk through this issue. Let’s learn what facades are, the arguments for and against them, and how to implement one. (You can find the sample code in this repository.)
I took this picture of the facade of Buckingham Palace when I was in London this November. Even though I know by looking at it that it’s Buckingham Palace, I have no idea what’s inside — and those guards are there to make sure I don’t find out.
In code, the term “facade” refers to the facade pattern, which is a structural design pattern from the famous book Design Patterns (usually called the “Gang of Four” in reference to the authors). Just like the front of a building hides what’s inside to passersby, a facade in code hides the complexity of underlying services by only exposing certain methods. You’ll often hear this hiding of complexity referred to as “adding a layer of abstraction.” An abstraction is a simpler and more general model of something that only provides what its consumer needs to know.
The facade pattern, and abstraction in general, is similar to the relationship between you and your car. You only need to know that when you turn the key and press the gas pedal, your car moves forward. You don’t need to care about the underlying mechanics of the engine or the science of combustion in order to go to the grocery store.
Here's how the facade pattern can be represened in a diagram:
You can see here how the clients don't know anything about the other services. They simply call doSomething() and the facade handles working with the services behind the scenes.
Recently, there has been a lot of discussion about whether or not to use a facade with NgRx to hide away bits like the store, actions, and selectors. This was sparked by an article by Thomas Burleson called NgRx + Facades: Better State Management. A facade is basically just an Angular service that handles any interaction with the store. When a component needs to dispatch an action or get the result of a selector, it would instead call the appropriate methods on the facade service.
If we were instead using a facade in the component, the class would look something like this (I’ll leave out the imports and decorator for the sake of brevity):