Monday, October 22, 2007

Anonymous Delegate Overuse Anti-Pattern

I like anonymous delegates and generics and use them both a lot. The combination affords considerable flexibility and allows me to keep my code DRY. However it's easy to take any technique too far. Just because you can do something doesn't mean that you should.

For example consider these two methods:
      private const string TEST_DATA = "1,2,3,4";

private string ToXml()
{
StringBuilder sb = new StringBuilder();
foreach (string s in TEST_DATA.Split(','))
{
sb.Append("" + s + "");
}
return sb.ToString();
}

private List ToList()
{
List list = new List();
foreach (string s in TEST_DATA.Split(','))
{
list.Add(s);
}
return list;
}
There is duplication in the two foreach blocks. It is possible to remove this using a combination of anonymous delegates and generics:
      private delegate void MyDelegate(T instance, string s);

private void Process(MyDelegate myDelegate, T instance)
{
foreach (string s in TEST_DATA.Split(','))
{
myDelegate(instance, s);
}
}

private string ToXmlUsingAnonymousDelegate()
{
StringBuilder sb = new StringBuilder();
Process(
delegate(StringBuilder tmp, string s)
{
tmp.Append("" + s + "");
}, sb);
return sb.ToString();
}

private List ToListUsingAnonymousDelegate()
{
List list = new List();
Process(
delegate(List tmp, string s)
{
tmp.Add(s);
}, list);
return list;
}
The resulting code is DRYer but it's definitely not easier to understand. If you had to maintain this how happy would you be?

0 Comments:

Post a Comment

<< Home