Revision as of 23:31, 12 January 2007 editEsotericengineer (talk | contribs)49 editsNo edit summary← Previous edit | Revision as of 23:31, 12 January 2007 edit undoEsotericengineer (talk | contribs)49 editsNo edit summaryNext edit → | ||
Line 96: | Line 96: | ||
] | ] | ||
] | ] |
Revision as of 23:31, 12 January 2007
In software engineering, a fluent interface (as first coined by Martin Fowler) is an objected oriented construct that defines a behavior capable of relaying the instruction context of a subsequent call. Generally, the context is
- defined through the return value of a called method
- self referential, where the new context is equivalent to the last context
This style is beneficial due to its ability to provide a more fluid feel ot the code, although some engineers find the the style difficult to read. A second criticism is that generally, programming needs are too dynamic to rely on the static contact definition offered by a fluent interface.
Example
The following example shows a class implementing a non-fluent interface, another class implementing a fluent counterpart of the aforementioned non-fluent interface, and differences in usage. The example is written in C#:
namespace Example.FluentInterfaces { using System;Categories:
public interface IConfiguration { void SetColor(string color); void SetHeight(int height); void SetLength(int length); void SetDepth(int depth); }
public interface IConfigurationFluent { IConfigurationFluent SetColor(string color); IConfigurationFluent SetHeight(int height); IConfigurationFluent SetLength(int length); IConfigurationFluent SetDepth(int depth); }
public class Configuration : IConfiguration { string color; int height; int length; int width;
void SetColor(string color) { this.color = color; }
void SetHeight(int height) { this.height = height; }
void SetLength(int length) { this.length = length; }
void SetDepth(int depth) { this.depth = depth; } }
public class ConfigurationFluent : IConfigurationFluent { string color; int height; int length; int width;
IConfigurationFluent SetColor(string color) { this.color = color; return this; }
IConfigurationFluent SetHeight(int height) { this.height = height; return this; }
IConfigurationFluent SetLength(int length) { this.length = length; return this; }
IConfigurationFluent SetDepth(int depth) { this.depth = depth; return this; } }
public class ExampleProgram { public static void Main(string args) { //Standard Example IConfiguration config = new Configuration(); config.SetColor("blue"); config.SetHeight(1); config.SetLength(2); config.SetDepth(3);
//FluentExample IConfigurationFluent config = new ConfigurationFluent().SetColor("blue") .SetHeight(1) .SetLength(2) .SetDepth(3); } } }