How to create a JavaScript library that is both functional and object-oriented?
When building a library, you may be faced with the choice of creating a functional API or an object-oriented one. This post is not concerned with the “politics” of these two programming paradigms. Instead, I am going to cover the practicalities of creating a library under each paradigm and finally suggest an approach, which would allow you to create a library that can cater to both.
A functional example
An object-oriented example
Usage Comparison
Immutability is essential to functional programming. Since we are trying to create a library that can be used under both paradigms, we can not use mutable data structures.
Bundle size is mainly a concern for browser code (not in Node.js). One option for addressing this concern in object-oriented code is by using module augmentation which is not going to be covered here.
So how do we create a library that can be used under both paradigms?
Simple. We write all of our logic as functional and immutable and then, we create an object-oriented wrapper around it and expose both of our definitions for usage.
Here’s how this would work:
There’s some effort involved in creating this OOP wrapper for all of your constructs. You could potentially reduce this overhead by doing it dynamically at runtime by looping over all the functional methods adding their object-oriented method wrappers to the prototype. This is not a good solution for TypeScript. Alternatively, you could write some sort of code generator to do this for you, but that’s not a small undertaking either.
Why should I bother?
By providing both of these interfaces, you could leave the choice of which paradigm to use to your users and allow them to make the choice that is right for them and their application.
The choice that you have to make as the creator of a library is whether this extra effort is something you wish to take on or not.
