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.
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: