Facade Design Pattern

About The Pattern

A Facade makes unpleasant things appear pleasant. This pattern gives your code an elegant interface to interact with, and behind this facade (interface) may lie some next-level complex interactions with multiple interfaces and third-party libraries.

Intro

If you've been coding for some time you've probably used the Facade pattern once or twice. Something along the lines of sync, render, compile... These are theoretically facades, hiding the complex inner workings.

I'm going to provide an example of how this pattern was used in building a part of this blog.

The Example

The markdown for each one of my posts follows this format.

---
title: Adapter Design Pattern
status: published
publishedDate: "2021-04-13"
---

## About The Pattern

An Adapter is a "wrapper" ...

There are a few steps we'd have to take to turn this markdown file into a post format that I can use in my blog.

  1. Take the file path of the markdown file and read it as a raw string

  2. Split string into 2 parts. The top part is the metadata, and the bottom is the post

  3. Convert part 1 (YAML) string into JSON

  4. Convert part 2 (markdown) string into HTML

This isn't a lot of steps nor is it complex but we can still wrap it all behind a nice interface.

Our ultimate goal is to take in a file path and have it return the metadata and HTML. It may look something similar like so:

type MdContent = {
  metadata: any,
  html: string,
};

class MdConverter {

  parseFilepath(filepath): MdContent {
    const fileData = fs.readFileSync(filepath, 'utf-8');
    const {
      metadataRaw,
      contentRaw,
    } = this.parseFileData(fileData);

    const metadata = yaml.load(metadataRaw);
    const html = md.render(contentRaw);
    return {
      metadata,
      html,
    };
  }
}

Now, whenever I need to parse my markdown files I can just create an instance of MdConverter and call one method, .parseFilepath, and be over with.

const md = new MdConverter();
const post = md.parseFilepath('path/to/a/post');

No one needs to care about how the converter works. If I need to improve the converter, I can just modify MdConveter and everyone will enjoy the benefits.

End

You can think of it like that global helper function you have in your codebase but we just turned it into a class 🌚