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:
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?
1 Answer 1
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 Build()
and make the method From
static instead. That simplifies the API.
Query.Build().From("SELECT * from TABLE").Where("FieldA > 20").Select("Field3").Create();
? \$\endgroup\$From(this-data-source).Where(this-environment).Select(this-configuration)
but currently it is possible to say just Select without specifying the other parameters. \$\endgroup\$