Fluent Interface is a pattern discovered by Eric Evans and Martin Fowler.
one problem of this pattern is  ”a mismatch between what a fluent interface needs and our usual guidelines for API design. What works well for a regular API doesn’t work for a fluent one and vice versa .” (Fowler)
So using FluentInterface we start adding setters that have a return value, others that they should not belong to the class in the API terms, but they do in Dsl terms.
Martin suggested an Expression Builder, which is a class that contains these bizar methods, But that means more classes, moreover, returning an interface of that Expression Builder that only contains allowed methods will add even more files and interfaces!
then He stated “dynamic languages work better for DSLs since they tend to have a less cluttered syntax. Using method completion, however, is a plus for static languages.”
Now if u ve been following c# news about the future version, then you absolutely heard of Extension Methods.
Extension methods are nothing but syntactic sugar, they are actuelly static methods that operate on a specific class, the following example illustraits better:
public static class Extensions
{Â Â Â public static bool IsNullOrEmpty(this string s)
   {
       // Notice I trim it too :)
       return (s == null || s.Trim().Length == 0);
   }
}class Program
{
   static void Main(string[] args)
   {
       string newString = null;
       if (newString.IsNullOrEmpty())
       {
           // Do Something
       }
   }
}so the compiler will turn this into a normal call of a static method so it will be Extensions.IsNullOrEmpty(newString) that helps to semplify the readibility of the code , and autoCompletion. But i agree that it is a dangerous feature and should be used with attention.Extension Methods will sit in classes in a namespace, that once u included, u can apply use them autoCompletion.Now the question is : Why do i relate this to the fluentInterface, i ll try to illustrate using to scinarios what can it bring to this pattern.
The first problem i talked about is returning the type when using a setter, that can be easily avoided by using extension methods. So that in the Class there are normal setters, but when u import the namespace using “using” keyword , you get AutoCompletion on the Weired Dsl friendly ,fluent interface’s this returning value setters :)
public static class ExpressionBuilder
{   public static Order With(this Order o,int id,string orderLine )
   {
       o.AddLine(new OrderLine(id,orderLine))
       return o;
   }   public static Order PriorityRush(this Order o )
   {
       o.SetRush(true);
       return o;
   }  Â
}class Program
{
   static void Main(string[] args)
   {
        Order o1= new Order();
       o1.With(6, “TAL”)
            .With(5, “HPK”).skippable()
            .With(3, “LGV”)
            .PriorityRush();
   }
}Here we can agree on somehting, the auto completion help without the need of knowing about another class which is the expression helper. But still the title says Dunamic? where is it?
ok that is my second scenario, the previous code looks really handy, but still i need to implement the moethds for each class, that is where the power of Generics and Reflection comes to the scene!
so what about an ExpressionBuilder where t:IFluentable
then the ExtensionMethods will be applicable to any Type that implements IFluentable, and will return their types!
but here, we still have to implement interfaces, and we cant have an IFluentable that works for all expression builder, what can we ease and facilate here is general cases, a very good example of such a generic fluent interface is Linq project , which works in IQuerable and IEnumerable, which will also be released in c# 3.0.
furthermore, reflection can be used inside the extension methods to discover properties that belong to the concrete class, and not only the interface.
i suggest reading about the Linq project, it is quite interesting good implementation of a Dsl language that is both, API and FluentInterface Friendly.
http://msdn2.microsoft.com/en-us/vcsharp/aa336746.aspx
 PS: There will be no need to specify the Types to the generic class and methods, thanks to Generics Type Inference that went well far in the C# 3.0 compiler!
you can already download a CTP (Demo) compiler of LINQ (including c# 3.0) from http://www.microsoft.com/downloads/details.aspx?familyid=1e902c21-340c-4d13-9f04-70eb5e3dceea&displaylang=en
Â
Â
Â
Â


[...] Interfaces fluentes Escrevendo a minha da próxima revista Mundo.Net, sobre ferramentas de Mock, tive contato com as interfaces fluentes. O Rhino Mocks permite que você estabeleça as expectativas do mock em uma interface fluente. Veja como fica o código: Expect.Call(MailerMock.SendMessage(”mail@host.com”)).IgnoreArguments().Return(5); //a mesma chamada em um layout mais fácil de entender Expect.Call(MailerMock.SendMessage(”mail@host.com”)) .IgnoreArguments() .Return(5); Ao invés de criar vários objetos e incluir cada objeto em uma propriedade do objeto principal, você simplesmente vai chamando os métodos um após o outro. Fica muito mais fácil de escrever o código, com menos linhas, e muito mais fácil de ler. É quase como uma frase separada por vÃrgulas. Com o código acima, por exemplo, você espera uma chamada no método SendMessage do objeto MailerMock, não quer validar os argumentos recebidos e quer forçar o retorno da chamada seja igual a 5. Achei bem interessante e resolvi implementar o exemplo que o Martin Fowler mostra no seu post sobre o assunto. Ele mostra o exemplo de uma criação de uma ordem de compra em uma linha de código. A coisa é mais simples do que parece a primeira vista. Comecei implementando as classes Customer, Order e OrderLine. Cada um tem suas propriedades, como nome, endereço de entrega, etc. O customer tem um método NewOrder que retorna um objeto Order. Até ai o código é “normalâ€, então tenho que criar o método With, que recebe os dados para criar uma OrderLine. O pulo do gato é retornar o próprio o objeto Order no método. O método ShipTo segue o mesmo princÃpio, recebe o endereço, grava na variável e retorna o this. public class Customer { private string _name; public string Name { get { return _name; } } public Customer(string name) { _name = name; } public Order NewOrder() { return new Order(this); } } public class Order { private Customer _customer; private List<OrderLine> _orderLines; private string _shipToAddress; public Customer Customer { get { return _customer; } } public List<OrderLine> OrderLines { get { return _orderLines; } } public string ShipToAddress { get { return _shipToAddress; } } public Order(Customer customer) { _orderLines = new List<OrderLine>(); _customer = customer; } public Order With(int itemId, float itemPrice) { _orderLines.Add(new OrderLine(itemId, itemPrice)); return this; } public Order ShipTo(string address) { _shipToAddress = address; return this; } } public class OrderLine { private int _itemId; private float _itemPrice; public int ItemId { get { return _itemId; } } public float ItemPrice { get { return _itemPrice; } } public OrderLine(int itemId, float itemPrice) { _itemId = itemId; _itemPrice = itemPrice; } } A criação da ordem tanto pode ser no método tradicional como utilizando a interface fluente, como mostra o código abaixo. //Modo tradicional Customer cust = new Customer(”Other Customer”); Order order = cust.NewOrder(); order.OrderLines.Add(new OrderLine(1, 5.0F)); order.OrderLines.Add(new OrderLine(2, 9.4F)); order.ShipTo(”My address”); //Modo fluente Customer cust = new Customer(”My Customer”); Order order = cust.NewOrder() .With(1, 10.0F) .With(2, 12.3F) .ShipTo(”My address”); Bom, não foi tão difÃcil em um exemplo simples, a coisa pode ficar bem mais complicada quando você quer forçar uma ordem para as chamadas ou limitar a quantidade de vezes que um método pode ser chamado. Algumas aplicações interessantes de interfaces fluentes: Rhino mocks – Mock object framework Readable regular expressions – um wrapper muito maneiro da API de regex do .Net Framework Fluent control container – Uma forma alternativa de instanciar controles ASP.Net Posts sobre aplicação prática de interfaces fluentes: A simple example of a fluent interface – Jon Galloway The Specification Pattern – Jeff Perrin Fluent Interface and c# 3.0 Extension Methods – Sadek Drobi [...]
Pingback by Console.Write(this.Opinion) : Interfaces fluentes — March 8, 2007 @ 12:51 pm
I wrote a article showing some “quick example” code illustrating how to build a (non-extended) Fluent Interface in C#:
http://blog.troyd.net/PermaLink,guid,5cdd4862-857a-488d-a577-c6d21b548f19.aspx
Thanks,
Troy
Comment by Troy DeMonbreun — September 24, 2007 @ 7:10 pm
“reflection can be used inside the extension methods to discover properties that belong to the concrete class, and not only the interface.”
You can avoid this using a combination of the builder pattern with generics and generic extension methods with generic constraints.
As an added benefit you’ll have compile time type safety.
I’ve blogged about it here:
http://withasmiletomeltathousandhearts.wordpress.com/2009/02/16/fluent-interfaces-constraints-at-compile-time/
Comment by jhonny — February 16, 2009 @ 5:34 pm