oopdesign-patternscircular-dependency

how to avoid circular dependencies here


Is there a way to avoid circular dependencies, other than mixing modules, in a arrangement like this(it is a chess application)

Long description:

AND HERE IS THE PROBLEM:

The Player module needs to know about other players and the board, thus importing ChessWorld!

Short description:

The World module needs to know about the Player module (even indirectly by Board/Piece) and Player need to know about World.

Help is very appreciated.

PS: Is not because I cant use circular dependencies, but because they are evil.


Solution

  • Follow the Dependency inversion principle: introduce an interface, which ChessWorld implements, and on which Player depends -- and/or one which Player implements and on which Piece depends (either or both may be appropriate depending on details on the nature of the dependency). This often goes together with Dependency Injection, and, if the dependant needs to dynamically instantiate a number of instance of the dependees, with Factory DPs.