Double dispatch

I never really divided things between entities and services in my game. Everything was just something and it seemed to work pretty nicely. Recently I started tinkering and trying to separate things into entities and services. Entities would be something that have identity and services don’t. Good example for entity is Character, which is used to represent player and various monsters in game. Good example for service is ActionFactory, that can be used to construct actions that make things happen in the world.

Previously, Character had dependency ActionFactory, meaning that everytime somebody wanted to construct a new Character object, he had to supply an ActionFactory object to it. This worked ok, but as soon as I start loading objects from persistent storage things get complicated. Services really shouldn’t be saved there after all, so I would have to load a Character and then later set ActionFactory dependency correctly. Sounds complicated and error prone.

Solution for this was to remove ActionFactory as a dependency from Character. Now new Character objects could be easily constructed and there wouldn’t be need to remember to add ActionFactory into it later. All those methods that previously used Character’s own ActionFactory now have extra parameter that is used to supply ActionFactory from outside.

def __init__(self, model, effects_collection, action_factory, rng):
...
def pick_up(self, item):
...

Is now:

def __init__(self, model, effects_collection):
...
def pick_up(self, item, action_factory):
...

I’m still on the edge, if it is a good solution or not, but I think it’s better than the previous one.

Also, did the same thing with Character and random number generator. Now unit testing combat is even simpler than before.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s