Friday, July 18, 2008 : 1:41 PM
- (0 comments)
Recently I've been talking to a developer friend of mine about Fluent Interfaces, due to a recent posting from Jason Olson... (yes, I realize I just put 3 links in a single sentence... I apologize).
Anyway, at first I brushed it off as yet another 'neat' thing that the development community is doing. But in some "quiet time", I decided to read up on what this really meant, and how it could help me as a developer. I have to say, I'm in love!
Within about 30 minutes, I understood what they were saying, and devised an example to myself to see if I really got it. Now, it could be that I missed the point 100% and that I'm just doing "method chaining", but hopefully, this is my rendition of a fluent interface to XML!
Why I Chose XML
First, I have to explain that I chose to write a fluent interface over XML because I hate working with XML in the .NET framework. Now, I will be fair and mention that LINQ to XML has made this a lot easier (and cleaner)... but I still hate it... plus I wanted to pick an easy example that I could explore.
Basically, I've only added functionality to write xml elements, xml attributes, text nodes and complex types. So, before I show you the code that I wrote to make the fluent interface class itself, I'll show you how I used it and what the result is. So here's my own code that I just came up with:
static void Main(string args)
string result = FluentInterfaceForXml
.WithText("I was born by the river!")
... and here's what the above results in:
That's some pretty hot code right there :)
My Fluent Interface Class
Hopefully you can understand what a fluent interface is now... unless I missed the point altogether :) So, you might be curious as to the code wrote to make this all happen... and it's simple really. Basically, I just made a simple C# class that has an XML document inside of it as a private field, and then when you call the ".WithNode" or ".WithAttribute" methods, I do the appropriate code that would give the desired results and return "this" back to the caller.
Here's the entire project. Take a look for yourself: SingingEels_FluentInterface_ForXML.zip