Is there a way to avoid circular dependencies, other than mixing modules, in a arrangement like this(it is a chess application)
Long description:
Gui
module which imports a ChessWidget
module;ChessWidget
just wraps the ChessWorld
module and imports CellButton
;CellButton
module imports the module Cell
;ChessWorld
module imports Board
(to represent it) and Players
(to notify them and fetch their moves);Board
module imports module Piece
;Piece
module imports module Player
;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.
To reduce or eliminate circular dependencies, architects must implement loose component coupling and isolate failures. One approach is to use abstraction to break the dependency chain. To do this, you introduce an abstracted service interface that delivers underlying functionality without direct component coupling.
There are a couple of options to get rid of circular dependencies. For a longer chain, A -> B -> C -> D -> A , if one of the references is removed (for instance, the D -> A reference), the cyclic reference pattern is broken, as well. For simpler patterns, such as A -> B -> A , refactoring may be necessary.
What Is a Circular Dependency? A circular dependency occurs when a bean A depends on another bean B, and the bean B depends on bean A as well: Bean A → Bean B → Bean A. Of course, we could have more beans implied: Bean A → Bean B → Bean C → Bean D → Bean E → Bean A.
You can, however, use the imported module inside functions and code blocks that don't get run on import. Generally, in most valid cases of circular dependencies, it's possible to refactor or reorganize the code to prevent these errors and move module references inside a code block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With