2

This post teaches us to separate object graph construction from the application logic into two different classes and the end goal is to have either: classes with logic OR classes with “new” operators. Sounds really nice, as coming from this post you can understand that if you have started to do DI you should do it completely and not partially to not break Law of Demeter. Thus you should use factories, where all the objects are created and then delegated to others by reference to create the object graph.

But what if I need to change the graph structure runtime? What if some object in the lower hierarchy is making this critical decision? (For example, I have 2 game scenes, and I want to switch from "InGame" scene to "MainMenu" scene if player hits to some object and that collision is detected below in the hierarchy.)

When I was reading this one I hoped that it will explain the solution. But actually, it didn't. So please tell me how to create new objects that change the software configuration and need lots of Injectables for changing it when they are in lower hierarchy.

One way to do this, is to pass the Factory, which creates the new config, down by the hierarchy, but this breaks the low of Demeter.

Other way is to use Observer Pattern and dispatch an event to the Factory, so that it can change the object graph structure, as it has all injectables and can build objects easily. After all, this is the work it does. But I am not sure, this is the right thing to do.

Please share your experience.

1

I believe the root concern here is the required lifetime of your dependencies, which is closely linked to the degree of abstraction vs specialisation within them.

If an object lower down the hierarchy needs to initiate a change in game scene, I would expect the dependency it would manipulate to be something like GameSceneManager with a .SetCurrentScene() method, as oppose to the dependency being an instance of a GameScene type which must be replaced with a new object.

An instance variable denoting the current GameScene may exist, but should be contained within the GameSceneManager object. The factory for creating such objects would be a dependency of the GameSceneManager object.

With this structure, the GameSceneManager object's lifetime is the same as the client object which depends on it, the object graph does not need to change when the scene is updated. Within the GameSceneManager object the instance variable holding the current GameScene object is updated with a new object, but from a factory which the client already knows about (has a reference to).

In this manner the law of Demeter is preserved, all dependencies can be injected during the initialisation of the object graph and need never be fundamentally changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.