Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to handle circular dependencies amongst objects?

In my code, I have the the following objects:

  • ErrorManager - controls how errors are logged in the application
  • ConfigManager - controls how the configuration information is obtained

On the project I'm working on, the ErrorManager needs to pull configuration information using the ConfigManager instance while the ConfigManager uses the ErrorManager incase an error occurs.

At the moment, I'm doing the following in code:

ErrorManager _errorManager = new CustomErrorManager();
ConfigManager _configManager = new CustomConfigManager(_errorManager);
_errorManager.SetConfigurationManager(_configManager);

Is there a way for me to clean up this circular reference of dependencies?

like image 488
JamesEggers Avatar asked May 06 '09 19:05

JamesEggers


People also ask

How do you resolve circular dependencies?

To resolve circular dependencies: Then there are three strategies you can use: Look for small pieces of code that can be moved from one project to the other. Look for code that both libraries depend on and move that code into a new shared library. Combine projectA and projectB into one library.

What is circular dependency error and how do you handle it?

When you see the circular dependency detected error displayed in your Google spreadsheet, this means that your formula is referring to a range that contains the formula itself, or in other words when the formula input, is dependent on the output.

What are circular dependencies among servers and how can they be avoided?

A circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers. While circular dependencies should be avoided where possible, you can't always do so.


2 Answers

I would create the following:

ErrorConfig _errorConfig = ...; 
// ErrorConfig is a new config object containing only ErrorManager Configuration
ErrorManager _errorManager = new CustomErrorManager(_errorConfig);
ConfigManager _configManager = new CustomConfigManager(_errorManager);

Now, the ConfigManager can can use the ready-to-run ErrorManager without a bootstrapping problem where the ErrorManager is not ready to handle errors.

like image 108
Alex B Avatar answered Dec 31 '22 19:12

Alex B


Circular references are usually best cleaned up by refactoring a third class that both depend on. For instance, you might have something like this:

BootstrapConfigManager _bcm = new BootstrapConfigManager();
ErrorManager _errorManager = new CustomErrorManager(_bcm);
ConfigManager _configManager = new CustomConfigManager(_bcm, _errorManager);
like image 33
Travis Jensen Avatar answered Dec 31 '22 19:12

Travis Jensen