Strongly Typed Event System

Yadi Yasheng
2 min readJan 12, 2021

--

decouple systems without sacrificing type safety

Photo by Sam Farallon on Unsplash

Event systems almost exist in all projects in some shape or form. It aims to provide a simple mechanism to allow miscellaneous subsystems to hook into core systems without cluttering the core too much. It’s commonly used for tracking data for analytics or achievement, interfacing user input with UI, or even notifying worker threads about job updates. It sure does have a wide range of applications.

Why I’m not a fan of it

basic implementation of event systems normally just use string as event id, and maybe pass along some variant data. It gets the job done, but things get out of hand very quickly. Random event strings everywhere, even if you save the event ids as global constants somewhere, it’s still easy to mess up the variant event payload. Let’s see if we can improve its maintainability a little.

Strongly Typed

Introducing typed events can help us get rid of raw strings and enforcing payload type.

Goal:

  1. avoid using raw strings as the main event identifier
  2. payload should be strongly typed
  3. minimal clutter

When designing systems, it’s always a good idea to “reverse” the process. With the goals in mind, let’s start from the API consumer’s point of view and work backward.

Here is what I expect the api would look like

Working backwards based on the desired interfaces, here is a gist demonstrating a basic event system enforcing typed events. It showcases the design of external interfaces, event storage, and delegate handing.

Not the focus of this write up but note that built-in concurrent data structures are used here to store events, to have a basic level of thread safety as well. Since event systems are also commonly used to communicate in between general worker, audio, or network threads.

--

--

Yadi Yasheng
Yadi Yasheng

Written by Yadi Yasheng

software engineer & game developer

No responses yet