Learn how Scala makes the builder pattern obsolete

UML diagram of Builder Pattern

I covered the Builder Design Pattern in Java using the example of a form field validator (1, 2, 3). Scala has features that make this pattern obsolete and that’s what this post is about.

Developers generally use the Builder pattern to accomplish one or more of these common goals:

  • Limit potential constructor parameter ordering bugs when constructing complex objects
  • Allow delay of object construction until all dependencies are met
  • Allow for an object to have optional parameters
  • Unclutter object construction

In addition, there may be other goals for the pattern.

The Builder pattern has some negatives. It moves construction logic out of the class it belongs to, or at least into an inner class. It adds extra code. It requires additional ceremony during object construction. And, finally, it can make it more difficult to figure out what is required to build the object and what is merely optional. This last point is such an issue that further elaborate schemes have been dreamed up. I almost didn’t post this link because it shows the use of the builder pattern in Scala. Don’t worry. That post was made before Scala 2.8 came out, killing it!

Scala 2.8 came out in 2009, with named and default parameters! These two features build in abilities (ha get it) that the builder pattern was attempting to supply. Check out Alvin Alexander’s short examples over at his blog and have fun shedding all the bloat of builders from your Scala code!


Leave a Reply

Your email address will not be published. Required fields are marked *