Wednesday, May 21, 2008
Strong typed CAB events
Out of pure guilt of not posting for 6 months (wow lazy), I thought i had better share some love.
Having been in the CAB space for a while and followed the EventTopics constants file pattern we have found that it can get very loosey goosey and have created a new pattern.
Only argument less events are defined in the EventTopics constants. Ie anything that just takes EventArgs.Empty goes in here.
///
/// Public CAB events that only require empty .
///
public class EventTopicNames : MyCompany.Cab.Infrastructure.Interface.Constants.EventTopicNames
{
///
/// The CAB event string to use to launch a customer search use case.
///
///
/// Only need to be provided as the event arguments.
///
public const string LAUNCH_CUSTOMER_SEARCH = "MyCompany.Examples.MyCustomerModule.Interface.LaunchCustomerSearch";
}
However if you need arguments passed with your event different rules apply. First, never use generic EventArgs. What a stupid idea generic EventArgs are. Take the 30seconds out of your life and create a strongly type event arg. Good practice tells us that in general it should be immutable so you can set the private field backing stores to readonly. Next provide arguments in the constructor to set any properties and then expose the properties. Also, seal the class as I bet no-one will want to inherit from you ultra specific CAB event arg.
Now, the event topic name belongs on this class. This now makes the whole thing so much more cohesive and discoverable.
public sealed class LaunchCustomerEditEventArgs : System.EventArgs
{
public const string CAB_ID = " MyCompany.Examples.MyCustomerModule.LaunchCustomerEditEventArgs";
private readonly int _customerId;
public LaunchCustomerEditEventArgs(int customerId)
{
_customerId = customerId;
}
public int CustomerId
{
get { return _customerId; }
}
}
Here I have used the convention of "CAB_ID" to expose the event topic name. That is just to satisfy the coding standards for the current company. I would prefer it to be "EventTopicName"
. Remember this needs to be constant so that it can be used in attribute on you publications and subscriptions. As it needs to be public and constant, changing it is a breaking change and requires all your dependant assemblies to recompile. To avoid the need to change it please give it a truly unique value. A good option is to use the full type name of the EventArgs.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment