My program is receiving data on a serial port, after the data is received it can be interpreted in one of eight different ways.
If I want to trigger an event after the data is received, should I use one event and use something like an enum in my custom event arg class, or should I create 8 separate events? Basically I am wondering what the convention is for creating events.
My assumption would be that a new event should be created when it is distinguishable from the current events, but I am not sure which way to go with my example.
Edit: To clarify the situation, the program predominantly will be communicating with a device over a serial port, the method that receives input is as follows:
Should I do this?
void receive(byte[] somebytes)
{
// After checking to make sure all bytes expected are received
switch(somecase)
{
case 0: TriggerEvent(SomeEventArgs);break;
case 1: TriggerEvent(SomeEventArgs);break;
case 2: TriggerEvent(SomeEventArgs);break;
case 3: TriggerEvent(SomeEventArgs);break;
case 4: TriggerEvent(SomeEventArgs);break;
case 5: TriggerEvent(SomeEventArgs);break;
case 6: TriggerEvent(SomeEventArgs);break;
case 7: TriggerEvent(SomeEventArgs);break;
case 8: TriggerEvent(SomeEventArgs);break;
}
}
OR this:
void receive(byte[] somebytes)
{
// After checking to make sure all bytes expected are received
switch(somecase)
{
case 0: Event0(LessEventArgs);break;
case 1: Event1(LessEventArgs);break;
case 2: Event2(LessEventArgs);break;
case 3: Event3(LessEventArgs);break;
case 4: Event4(LessEventArgs);break;
case 5: Event5(LessEventArgs);break;
case 6: Event6(LessEventArgs);break;
case 7: Event7(LessEventArgs);break;
case 8: Event8(LessEventArgs);break;
}
}
Both solutions will work, but I think it's much easier to have a signle event.
If you have a single event, you just have to define an unique
EventArgs<T>
publish a single event in your class, and handle a single event.All the logic to decide waht to do is in the "client class" that susbscribes to the event. This makes it easier to test and debug.
So you'd need:
If you do it this way, it's very easy to create a unit test to test the dispatcher method, and different unit tests to test each of the 8 methods.
Your "server class", which depends on external resoruces is simple. This is important becasue, it would be hard to debug an test the dispatcher that chose between eight events.
Think of the other implementaion, using 8 events: you'd get a more confusing and hard to test and debug code.
As a side note, I encourage you to read this thorough article on "C# Event Implementation Fundamentals, Best Practices and Conventions"