Use Case: Unit test object creation, any time object construction is complicated.
Definition
When piecewise object construction is complicated, provide and API for doing it in a brief and clearly expressed manner.
*A piecewise function is a function built from pieces of different functions over different intervals. *
Example FooBuilder
FooBuilder is used to construct the entity Foo, its state can be set if needs be with the methods WithId() and WithContactPerson(), this fluent API can be chained. Finally the Create() method returns an instance of Foo with the internal state set.
1 | namespace FooApp.Core.Builders |
Example Use Case Of FooBuilder
In a test this could be used as follows with the assumption fooRepository -> SelectList returns a collection of type Foo.
1 | var foo = new FooBuilder(); |
Example HTML Builder
Code example below from Dmitri Nesteruk
Life without Builder
Manually create some HTML, this will work but its not great.
1 | var sb = new StringBuilder(); |
Life With A Builder
Here the constructor for HtmlBuilder takes a rootName and the AddChild method takes childName and childText parameters. This is then encapsulating the creation and use of HtmlElement.
1 | // ordinary non-fluent builder |
The method AddChildFluent returns a HtmlBuilder to allow you to chain methods together. This works by returning a reference to the original object. This is called a fluent interface.
1 | var builder = new HtmlBuilder("ul"); |