How to improve the builder pattern?

后端 未结 10 890
野性不改
野性不改 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:15

    Question 1: Regarding the name of the pattern, I like the name "Step Builder":

    • http://rdafbn.blogspot.com/2012/07/step-builder-pattern_28.html
    • http://www.javacodegeeks.com/2013/05/building-smart-builders.html

    Question 2/3: Regarding pitfalls and recommendations, this feels over complicated for most situations.

    • You are enforcing a sequence in how you use your builder which is unusual in my experience. I could see how this would be important in some cases but I've never needed it. For example, I don't see the need to force a sequence here:

      Person.builder().firstName("John").lastName("Doe").build() Person.builder().lastName("Doe").firstName("John").build()

    • However, many times the builder needed to enforce some constraints to prevent bogus objects from being built. Maybe you want to ensure that all required fields are provided or that combinations of fields are valid. I'm guessing this is the real reason you want to introduce sequencing into the building.

      In this case, I like recommendation of Joshua Bloch to do the validation in the build() method. This helps with cross field validation because everything is available at this point. See this answer: https://softwareengineering.stackexchange.com/a/241320

    In summary, I wouldn't add any complication to the code just because you are worried about "missing" a call to a builder method. In practice, this is easily caught with a test case. Maybe start with a vanilla Builder and then introduce this if you keep getting bitten by missing method calls.

提交回复
热议问题