JavaWorld on OO: Getters/Setters vs Builder

后端 未结 4 1512
萌比男神i
萌比男神i 2020-12-28 19:31

Background:

I found this article on JavaWorld, where Allen Holub explains an alternative to Getters/Setters that maintains the principle that the implementation of

4条回答
  •  梦谈多话
    2020-12-28 20:02

    Question 1: String parsing seems strange. IMHO you can only do so much to anticipate future enhancements. Either you use a long parameter right from the start to be sure, or consider adding additional constructors later. Alternatively you can introduce an extensible parameter class. See below.

    Question 2: There are several scenarios in which the builder pattern can be useful.

    • Complex Object creation

      When you are dealing with very complex object that have lots of properties that you would preferably only set once at object creation, doing this with regular constructors can become hard to read, because the constructor will have a long list of parameters. Publishing this as an API is not good style because everyone will have to read the documentation carefully and make sure they do not confuse parameters.

      Instead when you offer a builder, only you have to cope with the (private) constructor taking all the arguments, but the consumers of your class can use much more readable individual methods.

      Setters are not the same thing, because they would allow you to change object properties after its creation.

    • Extensible API

      When you only publish a multi-parameter constructor for your class and later decide you need to add a new (optional) property (say in a later version of your software) you have to create a second constructor that is identical to the first one, but takes one more parameter. Otherwise - if you were to just add it to the existing constructor - you would break compatibility with existing code.

      With a builder, you simply add a new method for the new property, with all existing code still being compatible.

    • Immutability

      Software development is strongly trending towards parallel execution of multiple threads. In such scenarios it is best to use objects that cannot be modified after they have been created (immutable objects), because these cannot cause problems with concurrent updates from multiple threads. This is why setters are not an option.

      Now, if you want to avoid the problems of the multi-parameter public constructors, that leaves builders as a very convenient alternative.

    • Readability ("Fluent API")

      Builder based APIs can be very easy to read, if the methods of the builder are named cleverly, you can come out with code that reads almost like English sentences.

    In general, builders are a useful pattern, and depending on the language you are using, they are either really easy to use (e. g. Groovy) or a little more tedious (e. g. in Java) for the provider of an API. For the consumers, however, they can be just as easy.

提交回复
热议问题