Learn the Vanilla and Flavouring Pattern

Can you write code that is both reusable and specific enough for a beautiful design?

This pattern tries to tackle a difficult problem in coding: how do you make code that is generic and stable, but at the same time replaceable and specific?

Reusable specific code

In a top-down approach, one starts with a result in mind, and quickly iterate over the code until it produces the desired result. You may know this as Test Driven Development, but it works the same with you as a tester.

A button from Bit’s UI

Pretty straightforward. The button is a simple component with a border, border-radius and a color. You can even give it a small transformation so it would react when you click on it.

So far so good.

Unbeknownst to the button, in a different part of the code, another button is needed. One that is bolder, fuller, and more fitting to direct the user’s attention to whatever you want at the time.

It has a purple background, no border, and white text.

How does one make a new button?

Option 0: Create a new button from scratch

Yes this is a thing. Developers reinvent the wheel on a daily basis. Some of my best friends are dead Dependency Injection frameworks that people just have to write for themselves.

Custom specific code is easy to tailor and fits most corners easily. It even simplifies your whole codebase by tackling a piece of existence all by itself.

Of course it also means that you would have to update it manually for every single bug in the buttonshpere. Good luck with that.

Option 1: override using styles

As our button receives a classname, we could easily override the styles we’d like, and get the result we wanted.

However, this method is flawed — the new button still receives all the base styles from the original button, so it will inherit its future changes as well. For example, when we make the original button bold, the new button would also get this style.

To keep the new button consistent, we would have to review it and override the new styles. This can be time consuming and even difficult with some styles.

This violates the Open Close Principle. The component is open for extensions, but it is defiantly not closed to modifications. Such violation to the Pure base class can sometimes be worse than you would expect:

yikes! I haven’t even edited this, it was like that when I found it

Option 2: put a flag on it

UI Components are, basically, functions. You could pass parameters, and make logic around it. This is the structure in JSX, but it could work just as well in other formats.

<Button invert={true} onClick={ () => this.handleCatGifs()}/>

It makes sense in the first glance, until you realize it violates the Inversion of Control Principle. You would be trapped in a maintenance hell really fast.