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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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/

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}