Implementing a Pain-Free, Type Safe Event Engine

jonas

Well-Known Member
Task: Implement the Warcraft 3 event engine in C# or Java in a type safe, cohesive way, with low coupling
Problem: Different events have different data, so you need a way to distinguish between different events, handlers for different events, etc.


Slang:
interface IEvent (all events are objects of types that implement this interface)
interface IEventListener<E> where E : IEvent { void Handle(E event); }

or

interface IEventListener { void Handle(IEvent event); }
(listens to events of a specific type)

class Dispatcher { void Register???(IEventListener???); void Dispatch(IEvent e); }
(can register event listeners and broadcast events in an efficient manner).


Known Non-Solutions:
  • Cluttering the event type with all the accessors (violates type safety of the event)
  • Having a generic IEventListener<E> where E : IEvent type (then the dispatcher needs ListenersE1 : List<IEventListener<E1>>, ListenersE2 : List<IEventListener<E2>>, ..., because you can't mix instances of generics in a list - and whenever you create a new event, you have to change the code of the dispatcher in trivial ways)
  • Having IEvent with no accessors, IEventListener with method Handle(IEvent e) (because you lose type safety of the event, and you need to type check and cast inside of the Handle())
  • Having Handle<E>(E event), (because in the implementation of Handle you can't really know which type the event really is, so you can't access its fields etc.)
  • Implementing one HandleE method for each event type, because then whenever you want to add a new event you have to touch the IEventListener interface (or better, make it an abstract class with default No-Op behaviours; otherwise you have to touch all the implementations as well)
Solutions that don't work because of the type system:
  • Having Handle<E>(E event) and checking E at compile time with static if, implementing it as a no-op in "wrong" types
  • Allowing mixed generics in a list, and comparing the types
  • Using types like enums
  • ...
 
Last edited:

Accname

2D-Graphics enthusiast
How about something like this? (Note: I tried to keep it simple)
Code:
class EventDispatcherSystem {
 
   private final Map<Class<? extends Event>, EventDispatcher<?>> dispatchers = new HashMap<>();
 
   public <K extends Event> void fireEvent(K event) {
     @SuppressWarnings("unchecked")
     EventDispatcher<K> d = (EventDispatcher<K>) dispatchers.get(event.getClass());
     d.fireEvent(event);
   }
 
   public <K extends Event> void addEventListener(EventListener<K> listener) {
     Class<K> eventClass = listener.getEventClass();
     @SuppressWarnings("unchecked")
     EventDispatcher<K> d = (EventDispatcher<K>) dispatchers.get(eventClass);
     if (d == null) {
       d = new EventDispatcher<>();
       dispatchers.put(eventClass, d);
     }
     d.addEventListener(listener);
   }
 
}

class EventDispatcher<K extends Event> {
 
   private final List<EventListener<K>> listeners = new ArrayList<>();
 
   public void fireEvent(K event) {
     for (EventListener<K> l : listeners) {
       l.onEvent(event);
     }
   }
 
   public void addEventListener(EventListener<K> listener) {
     listeners.add(listener);
   }
 
}

interface Event {
   // Could have some kind of functionality
}

interface EventListener<E extends Event> {
 
   public void onEvent(E event);
 
   public Class<E> getEventClass();
 
}
You have one EventDispatcherSystem where you can register EventListener's and you can also fire Event's. Its pretty type safe except for 2 unchecked type casts which can not really be avoided in java. But we know for sure that these are safe because we make sure when registering EventListener's the generic types of the listener and the dispatcher fit each other. This compiles without problems on java. I have currently no C# compiler at hand but I am pretty sure you can do the same thing with C#.



Edit:
Here is also an example of how this can be used:
Code:
class UseCase {
  
   public static void main(String[] args) {
     EventDispatcherSystem eds = new EventDispatcherSystem();
    
     eds.addEventListener(new EventListener<StringEvent>() {
      
       public void onEvent(StringEvent event) {
         System.out.println("String: "+event.getValue());
       }
      
       public Class<StringEvent> getEventClass() {
         return StringEvent.class;
       }
     });
    
     eds.fireEvent(new StringEvent("ABC"));
    
     eds.fireEvent(new StringEvent("123"));
   }
  
}
 
Last edited:

jonas

Well-Known Member
Yes, I have also looked at a similar solution (mapping from Type to dispatcher), but couldn't find an equivalent for
Code:
 Class<? extends Event>, EventDispatcher<?>
in C#. Otherwise I could just do List<EventDispatcher<?>> , and already resolve the issues above.

This smells to me:
Code:
 dispatchers.get(event);
I know that a compiler can get this to work, but I would have expected something along the lines of event.getClass(), but I'm not so familiar with Java.

Thanks for your response, I'll see if C# also has these unspecified generics, or whatever is the appropriate search term. I find it hard to google for such things.
 

Accname

2D-Graphics enthusiast
Oh, that was indeed an error on my part. I didnt test it, I only compiled it. Stupid java doesnt check type for the get method.
 

jonas

Well-Known Member
Oh, that was indeed an error on my part. I didnt test it, I only compiled it. Stupid java doesnt check type for the get method.
May I jokingly remind you that the whole discussion was about a type safe implementation ;)
 

Accname

2D-Graphics enthusiast
By the way, one nice feature of this solution is that you can change the current EventDispatcher class into an EventDispatchStrategy interface and then implement different EventDispatchStrategy's as you need. You can even combine it with a factory pattern to change strategy implementations on the fly. This will give ou maximum flexibility and reusability.

One disadvantage of the current implementation is the fact, that sub-classes of event types will not be delivered to listeners for super classes.
For example: If we have the class StringEvent and then a subclass TimeSensitiveStringEvent. Then an EventListener<StringEvent> will not be notified of TimeSensitiveStringEvent's even though one would intuitively think they would.
This is why I would recommend, depending on the applications specific requirements, to iterate over all super classes of the event and notify all EventDispatcher's for all these types.

You could also improve the system to be safe against the lapsed observer problem (Link: https://en.wikipedia.org/wiki/Lapsed_listener_problem ). For this I would suggest using WeakReference within the List of EventDispatcher. You could also use a WeakHashMap within the EventDispatcherSystem.
 

jonas

Well-Known Member
I'm afraid in C# you really can't write down a type like that one. You have to put object as the domain of the map. But it won't make a big difference, since you use unsafe type casts anyways.

PS: to explain what I meant by more expressive type system: in Coq you could write
forall E : Type, extends E Event -> EventDispatcher E

In such a setting you really can get a type safe variant, where the correctness doesn't rely on the Programmer only using the map in a specific way. Which was what was originally the point of debate.

By the way, one nice feature of this solution is that you can change the current EventDispatcher class into an EventDispatchStrategy interface and then implement different EventDispatchStrategy's as you need. You can even combine it with a factory pattern to change strategy implementations on the fly. This will give ou maximum flexibility and reusability.
Not necessary, this thing is completely fixed.

One disadvantage of the current implementation is the fact, that sub-classes of event types will not be delivered to listeners for super classes.
For example: If we have the class StringEvent and then a subclass TimeSensitiveStringEvent. Then an EventListener<StringEvent> will not be notified of TimeSensitiveStringEvent's even though one would intuitively think they would.
This is why I would recommend, depending on the applications specific requirements, to iterate over all super classes of the event and notify all EventDispatcher's for all these types.
I'm aware of this but it is a yagni issue. I can't come up with a use case for event subclasses. Besides, you can just register yourself for all of the subclasses (C# can hopefully do this using contravariance with no extra effort).

You could also improve the system to be safe against the lapsed observer problem (Link: https://en.wikipedia.org/wiki/Lapsed_listener_problem ). For this I would suggest using WeakReference within the List of EventDispatcher. You could also use a WeakHashMap within the EventDispatcherSystem.
Listeners are actively managed in the program, so this is not an issue.
 

Accname

2D-Graphics enthusiast
Okay, here is a solution which uses the Visitor pattern to solve your buffered event problem: (This example is starting to become really really big!)
Code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UseCase {

   public static void main(String[] args) {
     EventDispatcherSystem eds = new EventDispatcherSystem();
     eds.addEventListener(new EventListener<StringEvent>() {
    
       public void onEvent(StringEvent event) {
         System.out.println("StringEvent: "+event.getValue());
       }
    
       public Class<StringEvent> getEventClass() {
         return StringEvent.class;
       }
     });
  
     eds.bufferEvent(new StringEvent("Test"));
     eds.dispatchAllEvents();
   }

}

class EventDispatcherSystem {

   private final Map<Class<? extends Event>, EventDispatcher<?>> dispatchers = new HashMap<>();
   private final List<Event> eventBuffer = new ArrayList<>();

   public void bufferEvent(Event event) {
     eventBuffer.add(event);
   }

   public void dispatchAllEvents() {
     for (Event ev : eventBuffer) {
       ev.dispatch(this);
     }
     eventBuffer.clear();
   }

   public <K extends Event> void dispatchEvent(K event) {
     @SuppressWarnings("unchecked")
     EventDispatcher<K> d = (EventDispatcher<K>) dispatchers.get(event.getClass());
     d.fireEvent(event);
   }

   public <K extends Event> void addEventListener(EventListener<K> listener) {
     Class<K> eventClass = listener.getEventClass();
     @SuppressWarnings("unchecked")
     EventDispatcher<K> d = (EventDispatcher<K>) dispatchers.get(eventClass);
     if (d == null) {
       d = new EventDispatcher<>();
       dispatchers.put(eventClass, d);
     }
     d.addEventListener(listener);
   }

}

class EventDispatcher<K extends Event> {

   private final List<EventListener<K>> listeners = new ArrayList<>();

   public void fireEvent(K event) {
     for (EventListener<K> l : listeners) {
       l.onEvent(event);
     }
   }

   public void addEventListener(EventListener<K> listener) {
     listeners.add(listener);
   }

}

interface Event {
   public void dispatch(EventDispatcherSystem eds);
}

interface EventListener<E extends Event> {

   public void onEvent(E event);

   public Class<E> getEventClass();

}

class StringEvent implements Event {

   private final String value;

   public StringEvent(String value) {
     this.value = value;
   }

   public String getValue() {
     return value;
   }

   public void dispatch(EventDispatcherSystem eds) {
     eds.dispatchEvent(this);
   }

}
The import part is now that the Event interface has a method "public void dispatch(EventDispatcherSystem eds) " which will be called by the EventDispatcherSystem. The implementation for the public "void dispatch(EventDispatcherSystem eds)" will be the very same for every implementing class of Event. They will call the "dispatchEvent(K)" method of the EDS with "this" as argument. Because each Event implementation knows its own type at compile time this will become type safe!


The above code compiles and works as intended (I tested it). You can copy + paste it into one file called UseCase.java. You should be able to compile and run it right away.
 
Last edited:

CandiceRoorm

New Member
Looks like dy/dx is becoming ex in the case of our dollar. I think if we used up all the Tech skills here in JA create a silicon island we could turn this around ??? :
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • jonas jonas:
    I think news.google shows you personalized news
  • midnight8 midnight8:
    any of the peeps in here run youtube channels? Figure of all the peeps in this forum, got to be some other geeks like me with channels
  • Ghan Ghan:
    I can say I've uploaded a YouTube video.
    +1
  • The Helper The Helper:
    I can say I know someone that uploaded a youtube video :)
  • jonas jonas:
    A friend of mine has a channel where he uploads some of the crazy machines he has built. Like when he plugged an electric motor into a 3d printed gearbox, attached it to his bycicle and then drove 50mph with it.
    +1
  • The Helper The Helper:
    You should post a link to his channel in General Discussion I would definitely check it out
  • The Helper The Helper:
    how hard is it to put google analytics on the site?
  • Ghan Ghan:
    Likely not hard. I think we've done it in the past. Anything in particular you want to see?
  • The Helper The Helper:
    I remember we are already getting stats
  • The Helper The Helper:
    I watch the members online area of the site to see what is being viewed from the past and let me tell you there are some gems I am finding in there
  • jonas jonas:
    you could tell us the gems
  • The Helper The Helper:
    I am trying to bump the gems when I find them
    +1
  • The Helper The Helper:
    look at the whats new section
  • The Helper The Helper:
    there is not much static in the last posts on the forum
  • The Helper The Helper:
    I think Tom Mai got sick of the news :(
  • Ghan Ghan:
    Hopefully he'll be back.
  • Ghan Ghan:
    Probably should renew support on our xenForo license one of these days....
  • The Helper The Helper:
    we can do that how much is it?
  • The Helper The Helper:
    55 bucks ask google lol
  • The Helper The Helper:
    donate link is gone there should be one
  • Ghan Ghan:
    Added
  • Ghan Ghan:
    xenForo license is paid through 2022.
  • Wizard Wizard:
    I also still float around. Whenever I'm needed, just have Ghan poke me.
  • Ghan Ghan:
    All these old staff members that haven't been online in years....

    Members online

    No members online now.

    Affiliates

    Hive Workshop NUON Dome
    Top