Events Are Your Friend
Use them well my friend.
Imagine trying to build a desktop application without events. How would you make a button click do what you want? One way would be to open the Button source code and add the code directly. That has approach has obvious problems, not the least of which is that the behavior of the button click will vary from button to button. Instead, maybe we would do something like this:
public class OkButton : Button{
protected override void Click()
{
Parent.Save();
}
}
This code is nice and clean at first glance. It would certainly be possible to write entire applications in this fashion. So, let me ask you a question. Why don't we write programs like this? Why do we use events instead?
Look back at the code block. Notice that our Click handler does not call the base class Click method. What if the base class needs to update the button appearance? Oops. Each time the object is inherited and extended, the chain of calls gets longer and the potential for this kind of thing to happen grows.
What if you wanted to be able to turn on or off certain behaviors at runtime? When you have a list of event handlers or observers, you can simply add or remove the handler. If you force class inheritance to modify behavior, what are you going to do? Codegen at runtime? Add booleans to each class that say whether or not to actually do something?
Events make enough sense that it is hard to imagine building a desktop application without them. Many developers, however, forget this when they start building server applications.
Instead of doing something like this:
public class OrderManager
{
public void PlaceOrder(Order o)
{
Save(o);
Bill(o);
SendConfirmationEmail(o);
}
}
Consider doing something like this:
public class OrderManager
{
public void PlaceOrder(Order o)
{
Save(o);
OrderPlaced(o);
}
public event OrderPlacedEvent OrderPlaced;
}
Now, when we decide we need an automated fulfillment system, we don't have to modify our order management system's code to support it. The fulfillment system simply needs to subscribe to the OrderPlaced event and it can do whatever it needs to do when an order is placed. When we switch from our home grown fulfillment system to vendor XYZ, we don't have to completely rework our code, we just have to swap out the old OrderPlaced handler with a new one.
Notice that we don't need MSMQ, Biztalk, an ESB, or a publish-subscribe framework to start heading in the right direction. In fact, you are better off coding things with generic event handlers to begin with, even if you are thinking about using something like MSMQ or an ESB. Build on the basics so that using MSMQ, deploying an ESB, or swapping ESB vendors, or calling other services will be just as easy as swapping out an event handler.
Events are your friend. Don't forget about them.