Skip to content
This repository was archived by the owner on Jun 7, 2019. It is now read-only.

Defensive coding: Builder of T

Yves Schelpe edited this page Dec 5, 2017 · 3 revisions

Builder<T> and SafeBuilder<T>

Provides an base type Builder<T> that makes it easier to start creating a basic builder for an object. SafeBuilder<T> provides an extra method which adds a method that checks whether an object can be built, if not it will throw an exception CanNotBuildException on runtime.

Limitations

This base builder class might not be the best option for each builder pattern. So before using these types, be aware of their limitations:

  • T needs to have an empty private constructor: private T() {}
  • One can only set public properties on the type, and the properties need to have a private set method.

Example

  • Setting the context, the object we're going to make a builder for is FakeObject
public class FakeObject
{
    public string String { get; set; }
    public int ReadOnlyInt { get; }
    public long PrivateSetterInt64 { get; private set; }
        
    private FakeObject() { } // needs to be provided
}
  • One can define a builder simply by making a class (e.g. FakeObjectBuilder) and inherit from Builder<T>.
public class FakeObjectBuilder : Builder<FakeObject, FakeObjectBuilder>
{
    // You can define your builder methods here in addition to the "With" method that's provided with the base class.
    // E.g.: WithInt64ToZero()
    public FakeObjectBuilder WithInt64ToZero()
        => With(x => x.PrivateSetterInt64, 0);
}
  • Using the builder can be done simply by creating a new instance and then starting the building process by chaining method calls of yourself, or with the With(x => x.Property, propertyValue) mechanism.

    • This will create an object that contains the value 36 for the property PrivateSetterInt64 on FakeObject
    var builder = new FakeObjectBuilder();
    var fakeObject = builder
                     .With(x => x.PrivateSetterInt64, 36)
                     .Build();
    
    • This will create an object that contains the value 0 for the property PrivateSetterInt64, and the value I'm building objects for the property String on FakeObject
    var builder = new FakeObjectBuilder();
    var fakeObject = builder
                     .With(x => x.String, "I'm building objects")
                     .WithInt64ToZero()
                     .Build();
    

Clone this wiki locally