C# : When to go Fluent
- by ach
In many respects I really like the idea of Fluent interfaces, but with all of the modern features of C# (initializers, lambdas, named parameters) I find myself thinking, "is it worth it?", and "Is this the right pattern to use?". Could anyone give me, if not an accepted practice, at least their own experience or decision matrix for when to use the Fluent pattern?
Conclusion:
Some good rules of thumb from the answers so far:
Fluent interfaces help greatly when you have more actions than setters, since calls benefit more from the context pass-through.
Fluent interfaces should be thought of as a layer over top of an api, not the sole means of use.
The modern features such as lambdas, initializers, and named parameters, can work hand-in-hand to make a fluent interface even more friendly.
...
Edit:
Here is an example of what I mean by the modern features making it feel less needed. Take for example a (perhaps poor example) Fluent interface that allows me to create an Employee like:
Employees.CreateNew().WithFirstName("Peter")
.WihtLastName("Gibbons")
.WithManager()
.WithFirstName("Bill")
.WithLastName("Lumbergh")
.WithTitle("Manager")
.WithDepartment("Y2K");
Could easily be written with initiallizers like:
Employees.Add(new Employee()
{
FirstName = "Peter",
LastName = "Gibbons",
Manager = new Employee()
{
FirstName = "Bill",
LastName = "Lumbergh",
Title = "Manager",
Department = "Y2K"
}
});
I could also have used named parameters in a constructors in this example.