How to improve the builder pattern?

后端 未结 10 874
野性不改
野性不改 2020-12-02 10:34

Motivation

Recently I searched for a way to initialize a complex object without passing a lot of parameter to the constructor. I tried it with the builder pattern,

相关标签:
10条回答
  • 2020-12-02 11:20

    No, it's not new. What you're actually doing there is creating a sort of a DSL by extending the standard builder pattern to support branches which is among other things an excellent way to make sure the builder doesn't produce a set of conflicting settings to the actual object.

    Personally I think this is a great extension to builder pattern and you can do all sorts of interesting things with it, for example at work we have DSL builders for some of our data integrity tests which allow us to do things like assertMachine().usesElectricity().and().makesGrindingNoises().whenTurnedOn();. OK, maybe not the best possible example but I think you get the point.

    0 讨论(0)
  • 2020-12-02 11:24

    The traditional builder pattern already handles this: simply take the mandatory parameters in the constructor. Of course, nothing prevents a caller from passing null, but neither does your method.

    The big problem I see with your method is that you either have a combinatorical explosion of classes with the number of mandatory parameters, or force the user to set the parameters in one particular sqeuence, which is annoying.

    Also, it is a lot of additional work.

    0 讨论(0)
  • 2020-12-02 11:28

    The Builder Pattern is generally used when you have a lot of optional parameters. If you find you need many required parameters, consider these options first:

    • Your class might be doing too much. Double check that it doesn't violate Single Responsibility Principle. Ask yourself why you need a class with so many required instance variables.
    • You constructor might be doing too much. The job of a constructor is to construct. (They didn't get very creative when they named it ;D ) Just like classes, methods have a Single Responsibility Principle. If your constructor is doing more than just field assignment, you need a good reason to justify that. You might find you need a Factory Method rather than a Builder.
    • Your parameters might be doing too little. Ask yourself if your parameters can be grouped into a small struct (or struct-like object in the case of Java). Don't be afraid to make small classes. If you do find you need to make a struct or small class, don't forget to refactor out functionality that belongs in the struct rather than your larger class.
    0 讨论(0)
  • 2020-12-02 11:30

    I've seen/used this:

    new ComplexBuilder(requiredvarA, requiedVarB).optional(foo).optional(bar).build();
    

    Then pass these to your object that requires them.

    0 讨论(0)
提交回复
热议问题