Over a million developers have joined DZone.

Breaking Dependency Cycles

DZone's Guide to

Breaking Dependency Cycles

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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/

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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


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

{{ parent.tldr }}

{{ parent.urlSource.name }}