Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Breaking Dependency Cycles

DZone's Guide to

Breaking Dependency Cycles

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

If you look into rules for good software design you’ll probably come around the notion that dependency circles(1) are bad. From my interview experience I’d say that many of the more experienced developers know that rule. And almost everybody agrees to that rule when asked. (Of course that might be due to the way I phrase the question. Some people say I can be pretty … convincing).

Anyway the logical next question is: How do you break circular dependencies? I find it a little disturbing that few developers can answer this question. So I’ll try to fix that.

Imagine two classes(2), forming a dependency circle. A depends on B and B depends on A. How do you break that circle, without changing the functionality? To be more precise: we are talking about the compile/deploy time dependency. At runtime the two classes need each others, so there actually will be a circular dependency.

Got it? It’s actually not that difficult: Extract all functionality of B into an interface C. Let A depend on C, B implements C and still depends on A. Circle broken.

Actually there is a piece missing. As said, at runtime we do need the circular dependency. At runtime A needs to reference an actual B. So you need a third class D which knows A and B and plugs the B into the A (using the C shaped hole).

Problem solved.

Actually this has a well known name: Dependency Injection. It should be quite easily doable without any framework in your main language.

Note (1): Larger circles are worse than smaller ones. Circles between classes of a single package are kind of ok. Circles between packages are pretty ugly. Circles between Jars are a no go and actually will break many tool chains.

Note (2): If you prefer you can replace the term ‘class’ with package or jar. In that sense a package implements another one, when it implements interfaces in that package.

 

From http://blog.schauderhaft.de/2011/07/17/breaking-dependency-cylces/

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}