Design Pattern: Facade Pattern [UPDATED]
“Software facades are a compromise: you are trying to expose just the functionality that you need while holding back the tide of complexity.” -Russ Olsen
The Facade Pattern is all about exposing a “simple and specific interface” to an otherwise complex system. It’s about convention and deciding what and how your system should be accessed. In the PPP book Uncle Bob refers to the Facade Pattern as “imposing policy from above” because when you build a facade you make those decisions.
The PPP book also had the easiest to understand example of a Facade Pattern. The facade was a class called “DB” that provided a simple and unified interface to the many classes required for using a database: creating, maintaining, connecting, cleaning up, etc.
Believe it or not, the Facade Pattern is a design pattern that actually didn’t make the cut for the Design Patterns in Ruby Book, and it’s a shame because the online draft chapter is full of nuggets like the quote at the beginning of this post. Olsen has a great run through of the patterns that are similar to the facade too and how they all differ:
“The facade is yet another of those patterns where an object stands in for one or more other objects. Facades and proxies and adapters and decorators all look something alike. But adapters exist to hide the fact that we are stuck using an object that has the wrong interface. A proxy stands between the user of an object and the object itself and somehow controls access to the object. And decorators add functionality to an object. The key idea behind a facade is that we are trying to simplify access to the object we are wrapping, the thing behind the curtain.”
I could see where the facade pattern would come in very handy when you’d want to simplify, but I do have one question. If you find yourself needing to simplify an interface, before implementing a facade shouldn’t you check to see that your code isn’t needlessly complex in the first place? I’ll definitely be asking around the office tomorrow.
UPDATE: Both Mike and Jim gave me some solid advice on the Facade Pattern today. They said that the pattern is often used when you don’t have control over the object that you’re applying the facade too. If it’s your own code then it would be worth taking a look at the complexity, but it’s quite often that you’re working with some sort of legacy codebase and need to simplify the interface it offers.