Patterncore
Facade pattern
Also called Facade, Façade, front end of a subsystem.
One object or module gives a single, higher-level interface to a subsystem of many classes. Clients call the facade, and the facade calls the subsystem in the right order.
- Family
- structural-design
- Intent
- Provide a unified interface to a set of interfaces in a subsystem, through a higher-level interface that clients can use with less knowledge of the subsystem.
- Refactorings
- Hide delegate, Remove middle man
Intent
Provide a unified interface to a set of interfaces in a subsystem. The facade defines a higher-level interface, so that clients can use the subsystem with less knowledge of it.1 Clients call the facade. The facade knows which classes of the subsystem to call, and in which order.
Problem
A compiler is a subsystem of many classes: a scanner, a parser, a builder of syntax trees, a code generator. A few clients need these parts one at a time. Most clients only want to compile a program. If each client must make the scanner, give its tokens to the parser and pass the tree to the code generator, then each client depends on all of these classes. Design Patterns starts from this example.1
The forces are these. A subsystem is easier to build and test when it is made of small classes. But small classes make a large surface for clients. Each client that uses the classes directly repeats the same steps, and it breaks when the subsystem changes. And some clients still need the small classes, so the subsystem must not hide them from everyone.
Solution
Design Patterns names two participants.1
- Facade knows which subsystem classes handle a request, and passes each request to the right objects.
- Subsystem classes do the work. They do not know about the facade and hold no reference to it.
Clients send requests to the facade. The facade may do some work of its own, such as putting the parts together, choosing the order of the calls, or undoing a step when a later step fails.
The examples model a shop with three parts: an inventory, a payment service and a shipping service. The facade has one operation, place_order. It reserves the item, charges the card, and schedules a parcel. When the charge fails, it puts the item back in stock. A client that calls the parts on its own must get these rules right each time. This one charges the card before it checks the stock:
This code runs but gives a wrong answer on purpose.
stock = {"lamp": 0}
charged = []
def charge(card, amount):
charged.append(amount)
return card != "expired"
def reserve(item):
if stock[item] == 0:
return False
stock[item] -= 1
return True
# A client that uses the subsystem directly, in its own order.
if charge("visa", 30.00):
if not reserve("lamp"):
print("failed: lamp is out of stock")
print(f"charged: {charged}")
failed: lamp is out of stock
charged: [30.0]
The customer paid for a lamp that the shop does not have. The facade puts the order of the steps in one place, so that every client gets the same order.
Facades and modules
A facade in a class-based language is often a class with one instance. Norvig lists Facade as the one pattern that modules make invisible. His slide on Facade says that a program with modules needs no bookkeeping objects or classes: it exports only the names that make up the interface.2 Most languages in the example files have this tool:
- A Go package exports a name only when it starts with an upper-case letter.7
- Items in a Rust module are private unless they are marked
pub. Apub usegives an item a public path, so a library can show one front for many inner modules.8 - A Java module declares which packages it exports. Other modules cannot use the classes of a package that is not exported.9
- A Python module has no private names. A leading underscore marks a name as internal, and an
__all__list gives the names thatfrom module import *imports.6 - In C, a header declares the facade, and
staticfunctions in the.cfile stay out of it.
With modules, the facade is the public part of the module, and the subsystem is the rest. No class is needed when the facade has no state of its own. When it has state, a class or a struct holds it, as in the Java and C# examples.
Facades and dependency injection
Design Patterns suggests two ways to reduce coupling between clients and the subsystem. Make the facade an abstract class with a concrete subclass for each implementation of the subsystem. Or configure the facade with the subsystem objects that it uses.1 The second way is constructor injection. The Java example passes the inventory, the payments and the shipping service to the constructor of Shop. A test can then pass fakes, and the facade does not hide which objects it depends on. The TypeScript example uses the first way: clients hold the interface Shop.
Example
All the example files run one script. A book order succeeds. A second book order fails at the payment, and the book goes back in stock. A lamp order fails, because the lamp is out of stock. At the end, one book is left.
| Language | Facade |
|---|---|
| Python | functions at the top level of a module, with private subsystem objects |
| JavaScript | a function that makes the subsystem and returns an object with two methods |
| TypeScript | an interface and a class that implements it |
| Java | a class that receives the subsystem through its constructor |
| C# | a class with a primary constructor and private fields |
| Go | the exported type of a package, over unexported types |
| Rust | the pub items of a module |
| C++ | a class over a detail namespace |
| C | the non-static functions of a file |
| SQL | a view over three tables |
# The subsystem: three classes, each with its own small job.
class Inventory:
def __init__(self, stock):
self._stock = dict(stock)
def reserve(self, item):
if self._stock.get(item, 0) == 0:
return False
self._stock[item] -= 1
return True
def release(self, item):
self._stock[item] += 1
def count(self, item):
return self._stock.get(item, 0)
class Payments:
def charge(self, card, amount):
return card != "expired"
class Shipping:
def __init__(self):
self._parcels = 0
def schedule(self, item):
self._parcels += 1
return self._parcels
# The facade: one function that calls the subsystem in the right order.
_inventory = Inventory({"book": 2, "lamp": 0})
_payments = Payments()
_shipping = Shipping()
def place_order(item, card, price):
if not _inventory.reserve(item):
return f"failed: {item} is out of stock"
if not _payments.charge(card, price):
_inventory.release(item) # undo the reservation
return f"failed: card declined, {item} back in stock"
parcel = _shipping.schedule(item)
return f"ok: {item}, paid {price:.2f}, parcel {parcel}"
def stock(item):
return _inventory.count(item)
print(place_order("book", "visa", 12.50))
print(place_order("book", "expired", 12.50))
print(place_order("lamp", "visa", 30.00))
print(f"stock of book: {stock('book')}")
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom. In Python, a module is the facade. A module
shopwould exportplace_orderandstock, and keep the subsystem objects as private names with a leading underscore. An__all__list names the public part forfrom shop import *. - The facade owns the order of the steps and the undo of the reservation. A client that called the three classes itself would have to repeat both.
- The subsystem classes stay public. A client that needs to read the inventory without an order can still use
Inventory. subprocess.runis a facade in the standard library. It starts aPopen, waits for the process, collects its output, and kills it on a timeout.
#include <format>
#include <iostream>
#include <map>
#include <string>
namespace detail { // the subsystem; by convention, clients do not use detail
class Inventory {
public:
explicit Inventory(std::map<std::string, int> stock) : stock_(std::move(stock)) {}
bool reserve(const std::string& item) {
auto it = stock_.find(item);
if (it == stock_.end() || it->second == 0) return false;
--it->second;
return true;
}
void release(const std::string& item) { ++stock_[item]; }
int count(const std::string& item) const {
auto it = stock_.find(item);
return it == stock_.end() ? 0 : it->second;
}
private:
std::map<std::string, int> stock_;
};
struct Payments {
bool charge(const std::string& card, double) const { return card != "expired"; }
};
class Shipping {
public:
int schedule(const std::string&) { return ++parcels_; }
private:
int parcels_ = 0;
};
} // namespace detail
// The facade.
class Shop {
public:
explicit Shop(std::map<std::string, int> stock) : inventory_(std::move(stock)) {}
std::string place_order(const std::string& item, const std::string& card, double price) {
if (!inventory_.reserve(item)) return std::format("failed: {} is out of stock", item);
if (!payments_.charge(card, price)) {
inventory_.release(item);
return std::format("failed: card declined, {} back in stock", item);
}
return std::format("ok: {}, paid {:.2f}, parcel {}", item, price, shipping_.schedule(item));
}
int stock(const std::string& item) const { return inventory_.count(item); }
private:
detail::Inventory inventory_;
detail::Payments payments_;
detail::Shipping shipping_;
};
int main() {
Shop shop({{"book", 2}, {"lamp", 0}});
std::cout << shop.place_order("book", "visa", 12.50) << "\n";
std::cout << shop.place_order("book", "expired", 12.50) << "\n";
std::cout << shop.place_order("lamp", "visa", 30.00) << "\n";
std::cout << "stock of book: " << shop.stock("book") << "\n";
}
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom.
Shopis the facade, and it holds the three subsystem objects by value. - C++ has no private namespaces. A
detailnamespace marks the subsystem as internal only by convention. A library hides it for real by keeping its header out of the public include directory. - A C++ module can export
Shopand not export the subsystem classes. Then a program that imports the module cannot name them.
import java.util.HashMap;
import java.util.Map;
public class Main {
static final class Inventory {
private final Map<String, Integer> stock;
Inventory(Map<String, Integer> stock) {
this.stock = new HashMap<>(stock);
}
boolean reserve(String item) {
int n = stock.getOrDefault(item, 0);
if (n == 0) {
return false;
}
stock.put(item, n - 1);
return true;
}
void release(String item) {
stock.merge(item, 1, Integer::sum);
}
int count(String item) {
return stock.getOrDefault(item, 0);
}
}
static final class Payments {
boolean charge(String card, double amount) {
return !card.equals("expired");
}
}
static final class Shipping {
private int parcels;
int schedule(String item) {
return ++parcels;
}
}
// The facade gets its subsystem objects through the constructor, so a test can pass others.
static final class Shop {
private final Inventory inventory;
private final Payments payments;
private final Shipping shipping;
Shop(Inventory inventory, Payments payments, Shipping shipping) {
this.inventory = inventory;
this.payments = payments;
this.shipping = shipping;
}
String placeOrder(String item, String card, double price) {
if (!inventory.reserve(item)) {
return "failed: " + item + " is out of stock";
}
if (!payments.charge(card, price)) {
inventory.release(item);
return "failed: card declined, " + item + " back in stock";
}
return String.format("ok: %s, paid %.2f, parcel %d", item, price, shipping.schedule(item));
}
int stock(String item) {
return inventory.count(item);
}
}
public static void main(String[] args) {
Shop shop = new Shop(new Inventory(Map.of("book", 2, "lamp", 0)), new Payments(), new Shipping());
System.out.println(shop.placeOrder("book", "visa", 12.50));
System.out.println(shop.placeOrder("book", "expired", 12.50));
System.out.println(shop.placeOrder("lamp", "visa", 30.00));
System.out.println("stock of book: " + shop.stock("book"));
}
}
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom.
Shopis the facade. It holds the three subsystem objects and has one method for each task that a client needs. - The constructor takes the subsystem objects, so the code that builds the program chooses them, and a test can pass fakes. This is dependency injection, and it keeps the facade from hiding which objects it uses.
String.formatwith%.2fuses the default locale. A program that must print a dot in every locale passesLocale.ROOT.- A Java module can export the package of the facade and not export the packages of the subsystem. Code in other modules then cannot use the subsystem classes at all.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/* The subsystem. In a real program each part has its own .c file, and these
functions are static or declared only in a private header. */
struct item {
const char *name;
int stock;
};
static struct item inventory[] = {{"book", 2}, {"lamp", 0}};
static int parcels = 0;
static struct item *find(const char *name) {
for (size_t i = 0; i < sizeof inventory / sizeof inventory[0]; i++) {
if (strcmp(inventory[i].name, name) == 0) {
return &inventory[i];
}
}
return NULL;
}
static bool reserve(const char *name) {
struct item *it = find(name);
if (it == NULL || it->stock == 0) {
return false;
}
it->stock--;
return true;
}
static void release(const char *name) { find(name)->stock++; }
static bool charge(const char *card, double amount) {
(void)amount;
return strcmp(card, "expired") != 0;
}
static int schedule(void) { return ++parcels; }
/* The facade: the functions that a header shop.h would declare. */
void place_order(const char *name, const char *card, double price) {
if (!reserve(name)) {
printf("failed: %s is out of stock\n", name);
return;
}
if (!charge(card, price)) {
release(name);
printf("failed: card declined, %s back in stock\n", name);
return;
}
printf("ok: %s, paid %.2f, parcel %d\n", name, price, schedule());
}
int stock(const char *name) {
struct item *it = find(name);
return it == NULL ? 0 : it->stock;
}
int main(void) {
place_order("book", "visa", 12.50);
place_order("book", "expired", 12.50);
place_order("lamp", "visa", 30.00);
printf("stock of book: %d\n", stock("book"));
return 0;
}
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom. In C, a header file is the facade. It declares
place_orderandstock, and the subsystem functions arestatic. Astaticfunction has internal linkage, so other files cannot call it by name. - The state of the subsystem is in
staticvariables of one file. A facade with more than one shop would take a pointer to an opaquestruct shopthat only the.cfile defines.
var shop = new Shop(new Dictionary<string, int> { ["book"] = 2, ["lamp"] = 0 });
Console.WriteLine(shop.PlaceOrder("book", "visa", 12.50m));
Console.WriteLine(shop.PlaceOrder("book", "expired", 12.50m));
Console.WriteLine(shop.PlaceOrder("lamp", "visa", 30.00m));
Console.WriteLine($"stock of book: {shop.Stock("book")}");
sealed class Inventory(Dictionary<string, int> stock)
{
public bool Reserve(string item)
{
if (stock.GetValueOrDefault(item) == 0) return false;
stock[item]--;
return true;
}
public void Release(string item) => stock[item] = stock.GetValueOrDefault(item) + 1;
public int Count(string item) => stock.GetValueOrDefault(item);
}
sealed class Payments
{
public bool Charge(string card, decimal amount) => card != "expired";
}
sealed class Shipping
{
int _parcels;
public int Schedule(string item) => ++_parcels;
}
// The facade: one class with the two operations that clients need.
sealed class Shop(Dictionary<string, int> stock)
{
readonly Inventory _inventory = new(new Dictionary<string, int>(stock));
readonly Payments _payments = new();
readonly Shipping _shipping = new();
public string PlaceOrder(string item, string card, decimal price)
{
if (!_inventory.Reserve(item)) return $"failed: {item} is out of stock";
if (!_payments.Charge(card, price))
{
_inventory.Release(item);
return $"failed: card declined, {item} back in stock";
}
return $"ok: {item}, paid {price.ToString("F2", System.Globalization.CultureInfo.InvariantCulture)}, parcel {_shipping.Schedule(item)}";
}
public int Stock(string item) => _inventory.Count(item);
}
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom.
Shopis the facade. It makes its subsystem objects and keeps them in private fields. - The price is a
decimal, which holds12.50exactly. Money in adoublecan show rounding errors. - In a library, the subsystem classes would be
internal, so code in other assemblies sees onlyShop. - An ASP.NET Core application would register the subsystem classes with the dependency injection container, and the container would pass them to the constructor of
Shop.
class Inventory {
#stock;
constructor(stock) {
this.#stock = new Map(Object.entries(stock));
}
reserve(item) {
const n = this.#stock.get(item) ?? 0;
if (n === 0) return false;
this.#stock.set(item, n - 1);
return true;
}
release(item) {
this.#stock.set(item, this.#stock.get(item) + 1);
}
count(item) {
return this.#stock.get(item) ?? 0;
}
}
class Payments {
charge(card, _amount) {
return card !== "expired";
}
}
class Shipping {
#parcels = 0;
schedule(_item) {
return ++this.#parcels;
}
}
// The facade: a function that makes the subsystem and returns only two operations.
function createShop(stock) {
const inventory = new Inventory(stock);
const payments = new Payments();
const shipping = new Shipping();
return {
placeOrder(item, card, price) {
if (!inventory.reserve(item)) return `failed: ${item} is out of stock`;
if (!payments.charge(card, price)) {
inventory.release(item);
return `failed: card declined, ${item} back in stock`;
}
return `ok: ${item}, paid ${price.toFixed(2)}, parcel ${shipping.schedule(item)}`;
},
stock: (item) => inventory.count(item),
};
}
const shop = createShop({ book: 2, lamp: 0 });
console.log(shop.placeOrder("book", "visa", 12.5));
console.log(shop.placeOrder("book", "expired", 12.5));
console.log(shop.placeOrder("lamp", "visa", 30));
console.log(`stock of book: ${shop.stock("book")}`);
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom. A function makes the subsystem objects and returns an object with the operations of the facade. The subsystem objects are local variables, so a client cannot reach them through
shop. - In a program with ES modules, the module is the facade. It exports
placeOrderandstockand does not export the classes. - The facade is a plain object, not a class. A test can replace it with another object that has the same two methods.
class Inventory {
private readonly stock: Map<string, number>;
constructor(stock: Record<string, number>) {
this.stock = new Map(Object.entries(stock));
}
reserve(item: string): boolean {
const n = this.stock.get(item) ?? 0;
if (n === 0) return false;
this.stock.set(item, n - 1);
return true;
}
release(item: string): void {
this.stock.set(item, (this.stock.get(item) ?? 0) + 1);
}
count(item: string): number {
return this.stock.get(item) ?? 0;
}
}
class Payments {
charge(card: string, _amount: number): boolean {
return card !== "expired";
}
}
class Shipping {
private parcels = 0;
schedule(_item: string): number {
return ++this.parcels;
}
}
// The interface that clients see. It names no subsystem class.
interface Shop {
placeOrder(item: string, card: string, price: number): string;
stock(item: string): number;
}
class ShopFacade implements Shop {
private readonly inventory: Inventory;
private readonly payments = new Payments();
private readonly shipping = new Shipping();
constructor(stock: Record<string, number>) {
this.inventory = new Inventory(stock);
}
placeOrder(item: string, card: string, price: number): string {
if (!this.inventory.reserve(item)) return `failed: ${item} is out of stock`;
if (!this.payments.charge(card, price)) {
this.inventory.release(item);
return `failed: card declined, ${item} back in stock`;
}
return `ok: ${item}, paid ${price.toFixed(2)}, parcel ${this.shipping.schedule(item)}`;
}
stock(item: string): number {
return this.inventory.count(item);
}
}
const shop: Shop = new ShopFacade({ book: 2, lamp: 0 });
console.log(shop.placeOrder("book", "visa", 12.5));
console.log(shop.placeOrder("book", "expired", 12.5));
console.log(shop.placeOrder("lamp", "visa", 30));
console.log(`stock of book: ${shop.stock("book")}`);
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom. The interface
Shopis the facade's contract, andShopFacadeimplements it. Clients depend onShopand import nothing from the subsystem. - Design Patterns suggests an abstract facade for this reason: a client that holds the interface can work with another implementation of the subsystem.
privateis checked only bytsc. At run time the fields are normal properties, so the JavaScript example uses closures to hide them.
package main
import "fmt"
// The subsystem types are unexported, so code outside this package cannot use them.
type inventory struct{ stock map[string]int }
func (i *inventory) reserve(item string) bool {
if i.stock[item] == 0 {
return false
}
i.stock[item]--
return true
}
func (i *inventory) release(item string) { i.stock[item]++ }
type payments struct{}
func (payments) charge(card string, amount float64) bool { return card != "expired" }
type shipping struct{ parcels int }
func (s *shipping) schedule(item string) int {
s.parcels++
return s.parcels
}
// Shop is the facade, and it is the only exported type.
type Shop struct {
inv *inventory
pay payments
ship *shipping
}
func NewShop(stock map[string]int) *Shop {
return &Shop{inv: &inventory{stock: stock}, ship: &shipping{}}
}
func (s *Shop) PlaceOrder(item, card string, price float64) string {
if !s.inv.reserve(item) {
return fmt.Sprintf("failed: %s is out of stock", item)
}
if !s.pay.charge(card, price) {
s.inv.release(item)
return fmt.Sprintf("failed: card declined, %s back in stock", item)
}
return fmt.Sprintf("ok: %s, paid %.2f, parcel %d", item, price, s.ship.schedule(item))
}
func (s *Shop) Stock(item string) int { return s.inv.stock[item] }
func main() {
shop := NewShop(map[string]int{"book": 2, "lamp": 0})
fmt.Println(shop.PlaceOrder("book", "visa", 12.50))
fmt.Println(shop.PlaceOrder("book", "expired", 12.50))
fmt.Println(shop.PlaceOrder("lamp", "visa", 30.00))
fmt.Printf("stock of book: %d\n", shop.Stock("book"))
}
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: idiom. A Go package is the facade. A name that starts with an upper-case letter is exported, so
Shop,NewShop,PlaceOrderandStockare the interface, and the subsystem types are hidden. - In a real program the subsystem would be in its own package, or in an
internaldirectory, which only the packages near it may import. NewShopbuilds the subsystem. A version that takes the three parts as arguments lets a test pass fakes.
// The module is the facade. Only the items marked pub can be used outside it.
mod shop {
use std::collections::HashMap;
struct Inventory {
stock: HashMap<String, u32>,
}
impl Inventory {
fn reserve(&mut self, item: &str) -> bool {
match self.stock.get_mut(item) {
Some(n) if *n > 0 => {
*n -= 1;
true
}
_ => false,
}
}
fn release(&mut self, item: &str) {
*self.stock.entry(item.to_string()).or_insert(0) += 1;
}
}
struct Payments;
impl Payments {
fn charge(&self, card: &str, _amount: f64) -> bool {
card != "expired"
}
}
struct Shipping {
parcels: u32,
}
impl Shipping {
fn schedule(&mut self, _item: &str) -> u32 {
self.parcels += 1;
self.parcels
}
}
pub struct Shop {
inventory: Inventory,
payments: Payments,
shipping: Shipping,
}
impl Shop {
pub fn new(stock: &[(&str, u32)]) -> Self {
let stock = stock.iter().map(|&(k, v)| (k.to_string(), v)).collect();
Shop { inventory: Inventory { stock }, payments: Payments, shipping: Shipping { parcels: 0 } }
}
pub fn place_order(&mut self, item: &str, card: &str, price: f64) -> String {
if !self.inventory.reserve(item) {
return format!("failed: {item} is out of stock");
}
if !self.payments.charge(card, price) {
self.inventory.release(item);
return format!("failed: card declined, {item} back in stock");
}
let parcel = self.shipping.schedule(item);
format!("ok: {item}, paid {price:.2}, parcel {parcel}")
}
pub fn stock(&self, item: &str) -> u32 {
self.inventory.stock.get(item).copied().unwrap_or(0)
}
}
}
fn main() {
let mut shop = shop::Shop::new(&[("book", 2), ("lamp", 0)]);
println!("{}", shop.place_order("book", "visa", 12.50));
println!("{}", shop.place_order("book", "expired", 12.50));
println!("{}", shop.place_order("lamp", "visa", 30.00));
println!("stock of book: {}", shop.stock("book"));
}
ok: book, paid 12.50, parcel 1
failed: card declined, book back in stock
failed: lamp is out of stock
stock of book: 1
- Verdict: native. Items in a Rust module are private by default.
Shopand its threepubmethods are the only names thatmaincan use, so the compiler enforces the facade. - A library can make a facade over its inner modules with
pub use, which gives an item a public path in a different place. place_ordertakes&mut self, because an order changes the inventory and the parcel counter. The borrow checker then forbids two orders at the same time through oneShop.
CREATE TABLE items (name TEXT PRIMARY KEY, stock INTEGER NOT NULL);
CREATE TABLE reservations (item TEXT NOT NULL REFERENCES items (name), paid INTEGER NOT NULL);
CREATE TABLE parcels (id INTEGER PRIMARY KEY, item TEXT NOT NULL);
INSERT INTO items VALUES ('book', 2), ('lamp', 0);
INSERT INTO reservations VALUES ('book', 1);
INSERT INTO parcels (item) VALUES ('book');
-- The facade for reads: one view over three tables.
CREATE VIEW available AS
SELECT
i.name,
i.stock - (SELECT count(*) FROM reservations AS r WHERE r.item = i.name) AS free,
(SELECT count(*) FROM parcels AS p WHERE p.item = i.name) AS shipped
FROM items AS i;
SELECT printf('%s: %d free, %d shipped', name, free, shipped) FROM available ORDER BY name;
book: 1 free, 1 shipped
lamp: 0 free, 0 shipped
- Verdict: idiom. A view gives one query interface over several tables. A client reads
availableand does not need to know how stock, reservations and parcels are stored. The example runs in SQLite. - The view is a facade only for reads. In a database with stored procedures, such as PostgreSQL, a procedure that reserves, charges and ships inside one transaction is the facade for writes.
- A grant on the view and not on the tables makes the facade the only way in, as an unexported name does in a programming language.
Consequences
Design Patterns lists three consequences.1 A facade shields clients from the subsystem, so they deal with fewer objects. It gives weak coupling between the subsystem and its clients, so the subsystem can change without a change to the clients. A program can also use facades to layer a system: each layer talks to the next one through that layer's facade. And a facade does not stop clients from using the subsystem classes when they need to. A program can choose between the short path of the facade and the full control of the subsystem.
The last point is the main difference from information hiding. Design Patterns treats the subsystem classes as public or private as a separate question.1 A facade gives a short path for the common case. It is not a wall. Python's subprocess module shows this. Its documentation recommends run() for all the cases it can handle, and says that the underlying Popen interface can be used directly for advanced cases.4 The first call below is the facade, and the second is the subsystem under it:
import subprocess
import sys
command = [sys.executable, "-c", "print('hello')"]
# The facade: start, wait, collect the output, and check the timeout in one call.
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
print("run:", done.returncode, done.stdout.strip())
# The subsystem: the same work with Popen and communicate.
with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process:
out, _ = process.communicate(timeout=10)
print("popen:", process.returncode, out.strip())
run: 0 hello
popen: 0 hello
run itself is a facade over Popen. It makes a Popen, calls communicate, kills the process on a timeout or an error, raises CalledProcessError when check is true and the exit status is not zero, and returns a CompletedProcess.3
The costs are these. A facade is one more layer that a reader must go through. It can grow into a class that knows every part of the program, because each added task is a small change to it. And a facade that only passes each call through, with the same arguments, adds a layer and no value.
When not to use it
Do not write a facade over a subsystem that has one or two classes. The clients can use them directly.
Do not write a facade that forwards every method of one object. Fowler's refactoring Remove Middle Man removes such a class, so that clients call the delegate directly. It is the inverse of Hide Delegate, which adds a method to hide the delegate.1110 A facade should give a smaller or higher-level interface than the parts it covers.
Do not put business rules in the facade that belong to one part of the subsystem. The facade decides the order of the calls and the work that connects them. A rule about stock belongs in the inventory.
Do not write a facade class in a language that has modules, when the facade has no state. Export the functions of the interface and keep the rest private.2
Variants and related patterns
Adapter. An adapter changes the interface of one object to an interface that a client expects. A facade defines its own interface over many objects. See Adapter pattern.
Proxy and Decorator. A proxy and a decorator have the same interface as the one object that they wrap. A facade has its own interface. See Proxy pattern and Decorator pattern.
Mediator. Design Patterns compares the two. Both abstract the work of existing classes. A mediator handles the communication between colleague objects, and the colleagues know the mediator. A facade only abstracts the interface to a subsystem, and the subsystem does not know the facade.1
Abstract Factory. Design Patterns says that an abstract factory can work with a facade, to make subsystem objects in a way that does not depend on the subsystem. An abstract factory can also replace a facade, to hide the classes that are specific to a platform.1 See Abstract Factory pattern.
Singleton. Design Patterns notes that a program usually needs one facade object, so a facade is often a singleton.1 A module, or an object that the program makes once and passes to its clients, gives one facade without the costs of a global. See Singleton pattern.
Refactorings. Fowler's Hide Delegate adds a method to a class, so that its clients do not reach through it to the delegate. Remove Middle Man is its inverse.1011
Known uses
- Python:
subprocess.runis a facade overPopen,communicate,killandCalledProcessError. See its source at v3.14.0.34 - Python: the
shutilmodule offers high-level operations on files and collections of files, such as copying and removing. Its documentation points to theosmodule for operations on single files.5
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Facade (Intent, Motivation, Applicability, Participants, Collaborations, Consequences, Implementation, Related Patterns)
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (modules make Facade invisible) and slide 29 (Pattern, Facade)
- CPython v3.14.0 source, Lib/subprocess.py, function run, lines 512 to 579
- The Python Standard Library, subprocess, Python 3.14, Using the subprocess Module
- The Python Standard Library, shutil, Python 3.14, module introduction
- The Python Tutorial, Modules, Python 3.14, 6.4.1 Importing * From a Package
- The Go Programming Language Specification, Exported identifiers
- The Rust Reference, Use declarations, use Visibility
- The Java Language Specification, Java SE 25 Edition, 7.7 Module Declarations
- Martin Fowler, Refactoring catalog, Hide Delegate, catalog entry
- Martin Fowler, Refactoring catalog, Remove Middle Man, catalog entry (inverse of Hide Delegate)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag YG43AR Edit this page History Report an error Markdown