Question

I'm working with an external system which sends event-like data to us. An existing SDK from the third-party guys parses the JSON so in the end we get something like the following class:

public class Event
{
    public string Type;
    public dynamic Data;
}

The requirements are as follows:

  1. All events should have a default handler.

  2. Specific event types might have a handler which overrides the default one and does something else (code and logic duplication in handlers are not a concern as of now).

  3. Type of events may vary so we should be able to easily move the event from their specific handler to a default one or vice versa.

The solution which I thought of was to provide a dictionary with mapping of string to Type, where Type would be a handler type. Then, an appropriate handler would be created via reflection and an event would be passed to it to handle. If the key is not present in the dictionary, a default handler would be created. However, I'm not sure if it's the best way and I don't like to have three entries in the dictionary that point to one type, e.g.

'eventA' => handlerA

'eventB' => handlerA

'eventC' => handlerA

I haven't got a specific reason to dislike that, I just kinda feel that there might be a better way.

I also thought of using generics for that, but it's more of a vague idea and not a concrete concept right now.

Any suggestions on that? I'm pretty sure the issue is not unique but alas, I wasn't able to find a good wording to search.

Was it helpful?

Solution

There's probably others, but the three obvious solutions I can think of are:

  1. Use a Dictionary<string, HanderDelegate> map,
  2. Use a switch statement to map the "event" names to their handlers,
  3. Use OO polymorphism (one class per event type) and some sort of factory.

Each has their pros and cons. I personally would go with the dictionary solution, as you suggest. There is no "correct" answer here though.

OTHER TIPS

Your proposed design is good. I see no reason to object to it. There are possible alternative designs, but I can't think of anything decisively better.

If you have three types of events that are all handled by one handler, that information has to be encoded somewhere in any design. It might feel like "repetition", but it is not; it's three distinct pieces of information. So, don't worry about that.

Licensed under: CC-BY-SA with attribution
scroll top