"Hook" class for well-structured code architecture

I’m developing a chess-based deck builder game called Long Live The King. And I wanted to share a core class from my software design: the Hook

Imagine you start by coding the basic rules of chess. And then you start adding hundreds of elements which break those rules in different ways: Cards, status effects, special squares, non-standard chess pieces, bosses, etc. A new card might affect the rules for movement, or the rules for capturing. But you want to have all the code for this card encapsulated in a single class. Otherwise, with hundreds of different cards, the code for e.g. the movement function would quickly become an unmaintainable mess.

The Hook class can solve this dilemma.

Similar to a signal, a hook has a list of Callables and calls all of them when it is “triggered”. But Hook offers some more control compared to signals:

  • Hook allows to await the execution of it’s Callables
  • Hook can loop a return value through Callables
  • Hook allows to add or remove Callables from inside other subscribed Callables in the same invocation

The repository contains the Hook class plus a small sample project to showcase its usage.

1 Like