Facade Pattern — Design Patterns

A facade puts one simple door in front of several subsystems (parts of the code with their own jobs) that must be called in order. KancilCourier.send(service…

By the end of this lesson, Kancil Courier's checkout page writes just one line: KancilCourier.send("express", 2, "discount10"). Behind that line the price is calculated, a tracking number is taken, and the tracker is told, in the right order.

That's the Facade pattern at work: one simple door in front of several parts of the code (subsystems) that have to be called in a certain order. A subsystem is a part that does one job of its own, such as the shipping cost calculator. The caller calls one function, and the facade handles the order behind it. It's like a hotel receptionist. You say "check in, two nights". The receptionist checks the booking, records your ID, prepares the key card and tells housekeeping (the room cleaning department). You don't need to know that four departments are involved, or their order. But the receptionist doesn't set the room price: they only tell you the price that the bookings department set. In code, you are the caller, the receptionist is the facade, and each hotel department is one subsystem. The room price is a rule that stays in a subsystem, not in the facade.

The problem: every caller has to know four steps

Sending a parcel at Kancil Courier involves subsystems from earlier lessons: calculateShipping and PROMO (Strategy Pattern), trackingCounter (Singleton Pattern) and tracker (Observer Pattern). The checkout page, the app and the admin panel each write the same steps:

// checkout.js, app.js and admin.js each write this
const price = PROMO.discount10(calculateShipping("express", 2))
const trackingNo = trackingCounter.next()
const parcel = { trackingNo, service: "express", kg: 2, price, status: "picked_up" }
tracker.emit("status", parcel) // so it shows on the tracking page

There are three copies of the same four steps. If the admin's copy forgets the tracker.emit line, shipment KCL-0003 is still created and charged, but the tracking page answers "not found", with no error. If there's a new step, say registering every shipment with an insurance partner, three files change, and one will surely be missed.

Facade: one door for sending a parcel

In the facade version, the four steps move into one method, KancilCourier.send:

const KancilCourier = {
  send(service, kg, promo = "none") {
    const price = PROMO[promo](calculateShipping(service, kg)) // checked first, may throw
    const parcel = { trackingNo: trackingCounter.next(), service, kg, price, status: "picked_up" }
    tracker.emit("status", parcel)
    return parcel
  },
}

// checkout.js, app.js, admin.js only write:
const p = KancilCourier.send("express", 2, "discount10")
console.log(p.trackingNo + " $" + p.price.toFixed(2)) // KCL-0001 $32.40
without a facade with a facade
what a caller must know calculateShipping, PROMO, trackingCounter, tracker, and their order KancilCourier.send
a new step (insurance) changed in 3 files 1 line in send
steps that can be forgotten in every copy none, there's one copy

You've used facades often. In jQuery (a JavaScript library for changing the page), $("#tracking").addClass("active") hides DOM details behind one call. fetch(url) hides DNS (finding a server's address from a domain name), the connection and HTTP headers. Laravel also has a feature called Facades, for example Cache::get("key") or Mail::to($user)->send(...).

⚠️ Same name, different pattern. The Laravel docs call its Facades "static proxies". A call to Cache::get is passed to one object through __callStatic, a special PHP method that runs when code calls a static method the class doesn't have. That object is taken from the service container, the place where Laravel makes and keeps objects. So a Laravel Facade doesn't set the order of several parts. It is closer to a Proxy (a stand-in object that passes calls on to the real object). The way it gets its object is like the service locator (a way of getting the objects you need from one central place), which the Dependency Injection lesson covers.

A facade that grows into a god object

A facade easily becomes the place to put anything, because everyone already calls it. Take the 15% discount rule for gold members:

send(service, kg, promo = "none", member = "basic") {
  let price = PROMO[promo](calculateShipping(service, kg))
  if (member === "gold") price = price * 0.85 // a pricing rule inside the facade
  // ...
}

For a gold member, take a guess: what price does the cost-check page show (it still calls calculateShipping("express", 2) directly), and what is charged at checkout with no promo?

The cost-check page shows $36. At checkout, a gold member is charged 36 × 0.85 = $30.60. There are two prices for the same thing because the rule is hidden somewhere not every caller goes through. It belongs in PROMO, say PROMO.gold = (price) => price * 0.85, which the cost-check page can call too.

A year later, a facade like this can have 30 methods: send, refund, courier pay, monthly reports, promo emails. That's called a god object: one object that knows and does everything. Every team edits the same file, and every checkout test has to prepare every subsystem. A healthy facade stays thin: it only sets the order, with no business rules of its own (rules that come from how the business works, such as prices and discounts). When it starts to grow too big, split it by area: Shipping, Reports, Payroll.

Facade, adapter and decorator

Exercise: VideoConverter

In the exercise, you write a facade too, for video conversion. The starter (the code already in the editor) has three subsystems: readFile(path) returns "raw:" + path, decode(raw) returns "decoded:" + raw, and encode(decoded, format) returns "encoded:" + decoded + ":" + format. You fill in VideoConverter.convert(path, format) so it calls all three in order, then returns what encode gives:

step result for convert("movie.avi", "mp4")
readFile("movie.avi") raw:movie.avi
decode(...) decoded:raw:movie.avi
encode(..., "mp4") encoded:decoded:raw:movie.avi:mp4

The console then prints two lines: encoded:decoded:raw:movie.avi:mp4 and encoded:decoded:raw:clip.mov:webm. The exercise also checks convert("intro.mkv", "ogg"): the result must be encoded:decoded:raw:intro.mkv:ogg.

When you don't need a facade

⚠️ When does a facade start causing trouble?

TL;DR: A facade puts one simple door in front of several subsystems (parts of the code with their own jobs) that must be called in order. KancilCourier.send(service, kg, promo) calculates the price, takes a tracking number and tells the tracker. So the checkout page, the app and the admin panel don't copy four steps, and can't forget one. A facade only sets the order: formulas stay in the subsystems, and the subsystems can still be called directly. Business rules (rules from how the business works, such as discounts) inside a facade make two prices. A gold member sees $36 on the cost-check page, which doesn't go through the facade, but is charged $30.60 at checkout. A facade that swallows everything becomes a god object, one object that does everything. An adapter translates one shape, a decorator wraps with the same call, and a facade simplifies many parts. In the exercise, VideoConverter.convert calls three subsystems in order: return encode(decode(readFile(path)), format).

⚡ Four steps in every caller

Meaning: To send a parcel, the checkout page, the app and the admin panel each write the same four steps. The steps are: calculate the price, apply the promo, take a tracking number, then tell the tracker with tracker.emit so the parcel appears on the tracking page. If the admin's copy forgets tracker.emit, the shipment is still created and charged, but the tracking page answers "not found", with no error.

⚡ One simple door

Write:

const KancilCourier = {
  send(service, kg, promo = "none") {
    const price = PROMO[promo](calculateShipping(service, kg)) // checked first, may throw
    const parcel = { trackingNo: trackingCounter.next(), service, kg, price, status: "picked_up" }
    tracker.emit("status", parcel)
    return parcel
  },
}

Meaning: A facade puts one simple door in front of several subsystems (parts of the code with their own jobs) that must be called in order. Here the facade is KancilCourier.send, and it only sets the order: price formulas stay in calculateShipping and PROMO, and tracking numbers stay in trackingCounter. The price is calculated first, so a delivery service that doesn't exist is refused before a tracking number is wasted.

⚡ Keep the facade thin

Guess first: the gold member discount (price × 0.85) sits inside the facade. The cost-check page still calls calculateShipping("express", 2) directly, which gives 36. What price does a gold member see there, and what is charged at checkout for the same parcel through the facade, with no promo?

$36 on the cost check, $30.60 at checkout. Two prices for the same thing, because the cost check doesn't go through the facade.

Meaning: Put business rules, such as a member discount, in a subsystem such as PROMO, not in the facade. A facade that swallows everything becomes a god object, one object that knows and does everything: split it by area.

What you will learn