This repository was archived by the owner on Jun 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Defensive coding: Builder of T
Yves Schelpe edited this page Dec 5, 2017
·
3 revisions
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.
This base builder class might not be the best option for each builder pattern. So before using these types, be aware of their limitations:
-
Tneeds to have an empty private constructor:private T() {} - One can only set
public propertieson the type, and the properties need to have aprivate setmethod.
- 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 fromBuilder<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
36for the propertyPrivateSetterInt64onFakeObject
var builder = new FakeObjectBuilder(); var fakeObject = builder .With(x => x.PrivateSetterInt64, 36) .Build();- This will create an object that contains the value
0for the propertyPrivateSetterInt64, and the valueI'm building objectsfor the propertyStringonFakeObject
var builder = new FakeObjectBuilder(); var fakeObject = builder .With(x => x.String, "I'm building objects") .WithInt64ToZero() .Build(); - This will create an object that contains the value