Easily Applying a Fluent Builder Pattern to Javascript Classes

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?