iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Facade

The Facade pattern hides a messy subsystem behind a simple, well-named API. Callers don’t need to know about classes A, B, C and their wiring — they call one method on the facade.

Real-world facade examples

EXAMPLE
// 1) Video conversion facade — hides ffmpeg, codecs, paths
class VideoConverter {
    convert(input, format) {
        const probe = this.#probe(input);
        if (probe.video.codec === 'h264' && format === 'mp4') return this.#remux(input);
        const audio = this.#extractAudio(input);
        const video = this.#transcodeVideo(input, format);
        return this.#mux(video, audio, format);
    }
    #probe(file)            { return ffmpeg.probe(file); }
    #remux(file)            { return ffmpeg.remux(file, 'mp4'); }
    #extractAudio(file)     { return ffmpeg.extractAudio(file); }
    #transcodeVideo(f, fmt) { return ffmpeg.transcodeVideo(f, fmt); }
    #mux(v, a, fmt)         { return ffmpeg.mux(v, a, fmt); }
}

// Caller — no ffmpeg knowledge required
const out = new VideoConverter().convert('input.mov', 'mp4');

// 2) Email sending facade — hides Mailgun / SES / SMTP fallback
class Mailer {
    constructor({ mailgun, ses, smtp }) {
        this.providers = [mailgun, ses, smtp];
    }
    async send({ to, subject, text, html }) {
        const ts = Date.now();
        for (const p of this.providers) {
            try { return { id: await p.send({ to, subject, text, html }), provider: p.name, ts }; }
            catch (err) { /* try next */ }
        }
        throw new Error('all providers failed');
    }
}

// 3) The Browser's `fetch` is itself a Facade over DNS, TCP, TLS, HTTP/2, gzip, etc.
const { ok, json } = await fetch('/api/me').then(r => ({ ok: r.ok, json: r.json() }));

Why it matters

A Facade is great for boundaries you control AND for legacy code you can’t change but want to use cleanly. The trade-off is that callers can’t reach the underlying flexibility — design the API thoughtfully.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Hide a messy subsystem behind a tidy API.
class VideoConverter {
    convert(file, format) {
        const probe = ffmpeg.probe(file);
        return ffmpeg.transcode(file, format, probe.streams);
    }
}
Try it Yourself »

Discussion

Loading…