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:
For example consider these two methods:
private const string TEST_DATA = "1,2,3,4";There is duplication in the two foreach blocks. It is possible to remove this using a combination of anonymous delegates and generics:
private string ToXml()
{
StringBuilder sb = new StringBuilder();
foreach (string s in TEST_DATA.Split(','))
{
sb.Append("- ");
- " + s + "
}
return sb.ToString();
}
private ListToList()
{
Listlist = new List ();
foreach (string s in TEST_DATA.Split(','))
{
list.Add(s);
}
return list;
}
private delegate void MyDelegateThe resulting code is DRYer but it's definitely not easier to understand. If you had to maintain this how happy would you be?(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 ListToListUsingAnonymousDelegate()
{
Listlist = new List ();
Process(
delegate(Listtmp, string s)
{
tmp.Add(s);
}, list);
return list;
}
0 Comments:
Post a Comment
<< Home