Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular-dependency best practice

I'm currently writing a web scraper which retrieves information from the internet. Simplified it looks like this.

Data access project

  • Objects to retrieve raw data
  • Objects to parse the the raw data into objects (!!)
  • The entities that the parser returns.

Now, I'm creating the actual parser, and I'm going to use it like this:

using Application.DataAccess;
using Application.DataAccess.Entities;

namespace Application{
 public class TestScraper{
  public static ScrapeIt()
  {
   var source = DataAcces.Retriever.Retrieve("http://example.com");
   DataAccess.Entities.Entity entity = DataAccess.Parser.Parse(source);

   //Do stuf with source here.
  }
 }
}

As you can see, the Parser returns a Entity. However this is in the DataAccess namespace, yet, it makes no sense... it´s a circle, and I don´t really know how to fix this. Well I could come up with a few things, like creating another layer between those layers.

But I just want to know, how would YOU solve this. And what is a good (or the best practice) for this.

like image 885
Timo Willemsen Avatar asked Jan 19 '11 12:01

Timo Willemsen


People also ask

How do you deal with circular dependency?

Redesign. When we have a circular dependency, it's likely we have a design problem and that the responsibilities are not well separated. We should try to redesign the components properly so that their hierarchy is well designed and there is no need for circular dependencies.

Should I avoid circular dependency?

Ideally, circular dependencies should be avoided, but in cases where that's not possible, Nest provides a way to work around them. A forward reference allows Nest to reference classes that have not yet been defined by using the forwardRef() utility function.

How do you avoid circular dependencies?

Circular dependencies can be introduced when implementing callback functionality. This can be avoided by applying design patterns like the observer pattern.


1 Answers

You can fix a circular reference by factoring out the things that both classes refer to into a new class, and then the old classes both refer to the new class.

So in your case you could move the entities out of DataAccess and into perhaps a new Entities namespace, used by both DataAccess and Application.

By doing this you start with

A <--> D

and end up with

A --> E
D --> E
like image 58
Ed Guiness Avatar answered Sep 20 '22 02:09

Ed Guiness