Dependency Management – Reducing Dependency Cycles and Coupling

couplingdependency-injectionhierarchyobject-orientedsolid

I'm trying to learn how to produce quality object-oriented code and have been studying concepts like SOLID. I'm currently working on an entity-component-process system for a small game engine.

Currently, I have it implemented as such:

  • There is a ScreenStack which contains a stack of Screens
  • Each Screen has an EntityManager and ProcessManager.
  • The ProcessManager updates all Processes given entities from the EntityManager.
  • A Process handles all game logic, so it needs to be able to use ScreenStack to possibly push and pop screens. It can also create, remove, and change entities, so it needs the EntityManager from Screen. Basically a Process needs to know everything about the game since it affects so much of it, but it feels wrong.

How do I go about implementing this better? It seems like everything has a clear dependency hierarchy until you get to a process, where it gets thrown out the window.

There also seems to be tight coupling when I would want to push a new screen. Say, for example, I have a process in a MainMenu screen that checks for menu choice. If "New Game" is clicked, I need to push a new screen, which gets created at that moment. I've read that I shouldn't randomly throw in new which this seems to be doing.

Best Answer

I would suggest looking into "Tell Don't Ask" principle. Martin Fowler gives a good introduction here

The common implementation usually is based on messaging/notifications between the classes. Note, TDA is a "pure OOP" that object oriented languages are designed for. Unlike the most common mixed mode of OO+functional code together.

Another advice is to work on separation of queries from updates (do not allow code in same methods or even classes to request data and act on it) - that removes a lot of accidental complexity and greatly improves SRP.