Are anonymous Lambda style event handlers a readability killer?
3 min read
3 min read
public void SomeOtherMethod()Pretty straightforward. Now since C# 3.0 you have the possibility to declare anonymous methods of the type
{
MyClass aObj = new MyClass();
aObj.MyCustomEventName += new EventHandler(OnMyCustomEventName);
...
}
private void OnMyCustomEventName(object sender, EventArgs e)
{
//do what you need to
}
public void SomeOtherMethod()This makes it more concise since you define the event handling code directly at the point where you register the event.
{
MyClass aObj = new MyClass();
aObj.MyCustomEventName += delegate(Object sender, EventArgs e)
{
//do what you need to
};
}
public void someOtherMethod(){Note:
...
MyClass aObj = new MyClass();
aObj.setOnMyCustomEventListener(new IMyCustomEventListener(){
public void onMyCustomEvent(...){
//do what you need to
}
});
}
IMyCustomEventListener
is an interface and nevertheless we use the new to "instantiate" it. How's that possible? Well, this is a language
feature which behind instantiates an anonymous object implementing the according interface.public void SomeOtherMethod()Nice, isn't it? In this way defining an event is really fast. The only doubt I have is in terms of readability. Now clearly the example above is perfectly readable, but it is just a dummy example. But consider a method where you have to define lots of event handlers for different components. Then declaring all the handlers in the way above may soon get very smelly.
{
MyClass aObj = new MyClass();
aObj.MyCustomEventName += (s,e) =>
{
//do what you need to
};
}
RetrieveExpiredItems(aProductBag)
will do, but according to its name it will
retrieve the expired items from an object called aProductBag
and that may be enough because actually you
may be interested in something completely different. On the other side, if you code everything in one method you may
have substantial difficulties in finding the interesting piece because you're flooded with all the details you won't
even care about.