patterncsharpMinor
Guided object builder
Viewed 0 times
objectguidedbuilder
Problem
Sometimes when designing a fluent-api it's important to build an object in a specific way/sequence.
I tried to create such a guided builder and came-up with this:
Usage:
or
Without manual casting you are guided through the creation process so everything stays fluent. Or maybe there are better ways to suggest the fluent path?
I tried to create such a guided builder and came-up with this:
public class Query
{
public static IFrom Build() { return new Builder(); }
public class Builder : IFrom, IWhere, ISelect, ICreate
{
public IWhere From() { return this; }
public ISelect Where() { return this; }
public ICreate Select() { return this; }
public Query Create() { return new Query(); }
}
public interface IFrom { IWhere From(); }
public interface IWhere { ISelect Where(); ICreate Select(); }
public interface ISelect { ICreate Select(); }
public interface ICreate { Query Create(); }
}Usage:
var query1 = Query.Build().From().Where().Select().Create();or
var query2 = Query.Build().From().Select().Create();Without manual casting you are guided through the creation process so everything stays fluent. Or maybe there are better ways to suggest the fluent path?
Solution
As written in the comment, it reminds me of LINQ. So, maybe it make sense to write a Linq QueryProvider to use the familiar LINQ syntax.
If that is not an option:
I would drop the method
If that is not an option:
I would drop the method
Build() and make the method From static instead. That simplifies the API.Context
StackExchange Code Review Q#133181, answer score: 2
Revisions (0)
No revisions yet.