The Power of Constructors

Learn how constructs can be a powerful tool that can help us write clean and maintainable software.

Passing multiple parameters to a constructor with build()

SendMoneyCommand, our input model above, puts a lot of responsibility on its constructor. Since the class is immutable, the constructor’s argument list contains a parameter for each attribute of the class. And since the constructor also validates the parameters, it’s not possible to create an object with an invalid state.

In our case, the constructor has only three parameters. What if we have more parameters? Couldn’t we use the Builder pattern to make it more convenient to use? We could make the constructor with the long parameter list private and hide the call to it in the build() method of our builder. Then, instead of having to call a constructor with 20 parameters, we could build an object like this:

Get hands-on with 1200+ tech skills courses.