Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • There is the Gui module which imports a ChessWidget module;
  • ChessWidget just wraps the ChessWorld module and imports CellButton;
  • The CellButton module imports the module Cell;
  • The ChessWorld module imports Board (to represent it) and Players (to notify them and fetch their moves);
  • The Board module imports module Piece;
  • The 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.

like image 550
zaphnat Avatar asked Dec 26 '09 00:12

zaphnat


People also ask

How do you avoid circular dependencies?

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.

How do you overcome cyclic dependency?

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 circular dependency and how is it resolved?

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.

How do you avoid circular dependencies in Python?

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.


1 Answers

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.

like image 74
Alex Martelli Avatar answered Sep 22 '22 19:09

Alex Martelli