Start writing wrappers for external libraries

Let’s start with an example of a library method, uuid-js. uuid-js allows you to write random unique strings.

Commonly, you will probably just default to import the library function - it’s easy right? import uuid from ‘uuid’;

let idea = {
   id: uuid.v4(),
   title: 'my idea title'
};

But why should you create a wrapper?

Imagine a scenario where you import this function, hundreds, if not thousands of times throughout your code base. Sure, you could search and replace all occurrences. I wouldn’t rely on it though. You can import in various ways, which makes it more troubling.

import {v4} from 'uuid';

let uuid = v4();

Let’s say you search for the term v4 for the above example. You can’t replace all that term - it’s difficult to do. You’ll break the import if you replace v4 with another library, because you need to fix the uuid import also.

Testing

How can you test if the library will behave the same way you have previously used it? If you create a test, for example that generates two uuids at the same time, can you be sure the library handles them the same way?

test('creates two uuids', () => {
    const uuid_1 = v4();
    const uuid_2 = v4();

    expect(uuid_1).no.toBe(uuid_2);
})

If you create a wrapper, these problems go away and you can expect them to be the same.

function generateUUID() {
   return uuid.v4();
}

Now if you call this function, you don’t need to replace it across your code base. Just one place. You can also now test this function, making sure exactly it behaves as you intend.

Start by saving yourself from problems in the future - if you intend to replace, deprecate, or any other reasons! 🧪