Saturday, December 31, 2011

When working with nested structures like configuration or XML it is bit of pain with syntax in C#. Consider this code below. The object initializes in C# 3.0 helped a lot, but it's still pretty far from ideal. Important point here is readability, which is achieved thru nesting the initializers.

But there are downsides with approach above. You can't easily add same instance into 2 nodes. It forces you to declare pavel variable completely out of scope. And you can't use statements to prepare your data in place either. Note how Pavel is inserted after other employees into Developers team. The LINQ Select() helped great deal here, but it's not always possible to use it.
With more complex model and bigger tree to build, this will become unmanageable mess.

So, extension methods and lambdas to rescue. Do you like code below better ? I certainly do. I can use statements and variable declarations in inner scope. I get more dense and readable code.

How the extension method looks like ?

Below is extension method over external structure Department, which accepts same parameters as Team constructor. Inside is instance creations and adding to the collection.
Finally to allow the nesting of scopes, we pass the new instance to Action<> delegate.

Generate the extensions

The extension method above is nice and useful but it's quite boring to write it for each combination of container and child item. Multiplied by all constructor signatures.
So I decided to create ReflectionFluentator which can generate the code for you. It reads your model via reflection and generates the C# extensions.
See sample how to use the generator.

And the same thing for XML ? Sure.
You provide the XSD to XsdFluentator.
See sample how to use the generator.

Note that both generators are more prototypes than ready to ship. They don't handle any edge scenarios when reading the metadata or writing the code.
Fluentator is part of Polyglottos project. If you like the idea and wish to contribute improvements, please talk back.

At this point some of you may wonder what else could be made fluent this way. In my case, I realized that I need to generate the code and the code is just nested structure. So I created CodeDom code generator Polyglottos with fluent API. That's for another article next year. Enjoy the party tonight!