A nice post I passed through today: Fluent Interface.
It is a very nice programming style of adding "method-action" functionalities on an object. It makes you write less code and clear one! For instance, you can build Query-Like objects in an API using this style of fluent interface. Here is a sample code that shows how a C# object implements the fluent interface by adding "action-methods", where each method does a certain action "setting a value on an internal field" and return an instance of the object itself, here is the code:
public class CustomStringList
{
List<string> innerList = null;
public CustomStringList()
{
this.innerList = new List<string>();
}
public CustomStringList AddValue(string value)
{
this.innerList.Add(value);
return this;
}
public CustomStringList RemoveValue(string value)
{
this.innerList.Remove(value);
return this;
}
public int Count
{
get
{
return this.innerList.Count;
}
}
}
Now to use the above object, you can write something as:
CustomStringList stringList =
new CustomStringList()
.AddValue("ASP.NET")
.AddValue("Bilal")
.AddValue("Wessam")
.AddValue("Haissam")
.AddValue("Sami")
.AddValue("C#")
.RemoveValue("Bilal");
int numberOfElements= stringList.Count;
Hope you liked this post, as I am very impressed by this style and I have in mind so many ideas to build based on this fluent interface concept! You can read more on Fluent Interface here: http://en.wikipedia.org/wiki/Fluent_interface
Regards
Tags: