Easily Applying a Fluent Builder Pattern to Javascript Classes

Posted on:

Javascript is a free-for-all when it comes to mutable objects. js-builder-decorator can ensure your objects become read-only, with a clean builder interface.


As functional programmers are keen to remind us, immutability. is. awesome.

Immutable objects can’t be changed in any way, meaning they’re completely thread-safe, they’re easy to reason about, and values you depend on with them aren’t going to change unexpectedly. More and more languages are moving over to “immutable-first” thinking - that is, instead of adding a “const” or “final” keyword like in C++ or Java to stop an object changing, rather objects are immutable by default and require keywords like “mut” in Rust to make them mutable.

Javascript however, does not offer such keywords (ES6 is looking to change that however!) as of yet. Facebook’s immutable.js helps out, as does seamless-immutable.

A problem with these however, is they require all objects be constructed immediately before being passed in, and for classes with many fields, this can become cumbersome as the constructor may require many arguments to be passed in. The best solution to this “telescoping constructor” anti-pattern is the fluent-builder pattern.

What here, looks easier to read?

As you can see, the long constructor is unwieldy and confusing - it’s very easy to put arguments in the wrong way around, and any reader would have little idea what each argument exactly is. In Clean Code, Uncle Bob strongly warns us against any function with more than 3 parameters, and yet here we have 6, which could only grow!

By defining an EmployeeBuilder class, we’re able to have clearly readable code that can return us a fully constructed object.

“But Topher, writing a builder uses a lot of boilerplate, all of which needs testing and maintaining!”

While usually this is the case, I’ve written a helper class called BuilderDecorator, available on GitHub, which deals with all the cruft and boilerplate for you. Creating an immutable object then becomes as simple as the following example:


Have you had any problems with mutable objects, in Javascript or otherwise? What about immutable objects? Please share your stories below :)