i saw many example of Fluent style api development but some time i saw people implement fluent with interface and some time people use no interface just use straight forward class. i think people use fluent style api just due to chain of use….means easy access. so i like to know is there any other benefit of fluent api or interns of performance.
here is small code.
public class Coffee
{
private bool _cream;
public Coffee Make { get new Coffee(); }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
In your example, I think the syntax (i.e. the “ease of use”) is the only advantage. But for example LINQ methods work differently – the methods don’t return
this, they return a new instance. That is obviously a performance hit, but it enables the classes to be immutable, which helps tremendously when you reason about your code, it can promote parallel computations with such classes.Edit (example):
In that case, your
Coffeewould look like this (although it may not be a good example, because it doesn’t make much sense to me to use fluent syntax here anyway, let alone with new instances)But of course in case of such a simple class, it is always better to use constructor with parameters, e.g.
And as an opposite example, I remember a set of handy
Dictionaryextensions for adding items fluently, but without creating a new instance. Something like:Which you could use to fill a dictionary with some initial data for example