Tuesday, February 16, 2010

Fluent interface for hierarchical structures

Fluent interface works well in combination with builder pattern for representation of flat structures. But API gets a bit messy when you need represent some sort of hierarchical structure.

Currently I have “VeryVeryComplex” legacy entity and I need to represent it’s traversal algorithm in a friendly way. That looks easy when there is no arrays in the entity but as soon as it appears the code gets messy. The gist is to couple with hierarchy with a sort of collecting parameter pattern.

TouchEach method has 2 parameters: the collection to enumerate and “touch” delegate, that will be applied to each item in the collection. The delegate itself has also 2 arguments: t - toucher instance, that acts as a collecting parameter and i – collection element.

The consumer code would look like this:

var t = new Toucher();
var c = new VeryVeryComplexEntity();
t.Touch(c)
.Touch(c.Child1)
.Touch(c.Child2)
.TouchEach(c.SubCollection1
(t, i) => {
t.Touch(i.SubSubChild1)
.Touch(i.SubSubChild2);
// The same for Subcollection of i - item
});

Naive toucher implementation:


class Toucher
{
List<object> _items = new List<object>();
public Toucher Touch(object obj)
{
_items.Add(obj);
return this;
}
public Toucher TouchEach<T>(IEnumerable<T> collection, Action<Toucher, T> subTouch)
{
foreach(var i in collection)
{
subTouch(i, this);
}
return this;
}
}

Happy coding :).

No comments:

Post a Comment