How to design a Fluent Interface (Method Chaining)


 

Martin Fowler coined the term "FluentInterface" to describe objects that expose an interface that flows, and is designed to be readable and concise.  The cost of this fluency is additional effort required to design the interface for your object and the slight increase in complexity.  These types of interfaces are often utilized to create configurations for your objects but can progress into an internal Domain Specific Language or DSL.

  1. Person person = new Person();  
  2. person.Set.FirstName("Pat").LastName("Frank").Age(30).IsActive();  

Create an internal class that is accessed through a Set property and exposes only the Fluent Interface.

  1. public class Person  
  2. {  
  3.          public Person() {  _set = new PersonFluentInterface(this);               }  
  4. private string _firstName;  
  5. private string _LastName;  
  6. private int _age;  
  7. private readonly PersonFluentInterface _set;  
  8. private bool _isActive;  
  9. public PersonFluentInterface Set   {   get { return _set; }               }  
  10. public string FirstName      {   get { return _firstName; }   set { _firstName = value; }               }  
  11. public string LastName    {   get { return _LastName; }   set { _LastName = value; }               }  
  12. public int Age   {   get { return _age; }   set { _age = value; }               }  
  13. public bool IsActive  {   get { return _isActive; }   set { _isActive = value; }               }  
  14.           public class PersonFluentInterface  
  15.           {  
  16. private readonly Person _person;  
  17. public PersonFluentInterface(Person person) {      _person = person;                   }  
  18. public PersonFluentInterface FirstName(string firstName)   {     _person.FirstName = firstName;   return this;                   }  
  19. public PersonFluentInterface LastName(string lastName)    {     _person.LastName = lastName;   return this;                   }  
  20. public PersonFluentInterface Age(int age)    {     _person.Age = age;   return this;                   }  
  21. public PersonFluentInterface IsActive()   {   _person.IsActive = true;   return this;                   }  
  22. public PersonFluentInterface IsNotActive()    {    _person.IsActive = false;   return this;                   }  
  23. }           } 

Code to Live, Live to Code – How to design a Fluent Interface

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s