Circular dependencies
medium 45 minTwo classes or modules that need each other, directly or through others, form a cycle.
Video lesson · Chapter 1 of 6
Make a prediction
Circular dependencies
1:03Reel
Theory
Read or listen first. About 2 min.
What it is
A dependency is an arrow: A needs B to compile, to be created or to do its work. A circular dependency is a path of arrows that comes back to where it started: A to B to A, or A to B to C to A.
There are three kinds, and each has another cure. A module cycle: source files or packages import each other. A construction cycle: each object wants the other in its constructor. A call cycle: at run time A calls B, and B calls back into A before A has finished.
An interface removes a module cycle. It does not remove a construction cycle by itself, because the objects still need each other. This is the most common confusion about the subject, so name the kind first.
Why it exists
Start-up. If A must exist before B and B before A, neither can be first. You get a container error, a half loaded module, a null field or an endless recursion.
Testing and reuse. Parts of a cycle cannot be taken one by one. To test A you bring B, and B brings A again. The cycle is in truth one big part with several names.
Change. An edit travels around the ring. Without cycles there is an order of layers: the bottom can be built, tested and understood without the top.
A short history
1972
Robert Tarjan publishes an algorithm that finds strongly connected components in one walk over a graph. Cycle detectors still use it.
1979
David Parnas writes about designing software for ease of extension and contraction: the uses relation between parts should have no loops, so that useful subsets exist.
1996
John Lakos publishes Large-Scale C++ Software Design, which gives each component a level and shows ways to remove cycles between them.
1990s
Robert C. Martin names the acyclic dependencies principle: the graph of packages has no cycles.
2021
Spring Boot 2.6 prohibits circular references between beans by default. Until then field and setter cycles were resolved quietly.
Words to know
- Module cycle
- Files or packages import each other.
- Construction cycle
- Constructors need each other's objects.
- Call cycle
- A calls B, which calls A again, at run time.
- DAG
- Directed acyclic graph: arrows without a way back.
- Topological order
- An order in which everything comes after what it needs. It exists exactly when there is no cycle.
- Strongly connected component
- A largest group in which every member can reach every other. More than one member, or a self loop, means a cycle.
- Composition root
- The one place that creates the objects and connects them, in topological order.
- Port
- A small interface owned by the side that calls it.
- Mediator
- A third object that both sides know, so that they need not know each other.
- Reference cycle
- Objects that keep each other alive in memory. Related by name, but a question of memory.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Draw the arrows. Who needs whom, and for what
Understand it
Start here
Two locked boxes
Sam has a red box, Asha has a blue box. Each was locked with the other key inside. Both boxes have a window, so everybody can see the problem, and nobody can open anything.
Another cousin: two cars meet on a narrow bridge, and each waits for the other to go back. A traffic light, a one-way sign or a second road solves it.
The problem
Orders need customers, customers need orders
OrderService needs CustomerService to check a customer. CustomerService needs OrderService to show the history. Each wish is reasonable. Together they are a ring.
The bad shape: a ring of two
1/3First arrow
Placing an order checks that the customer exists.
uses
class A: def __init__(self, make_b): self.b = make_b() # construction cycleclass B: def __init__(self, make_a): self.a = make_a()def make_a(): return A(make_b)def make_b(): return B(make_a)try: make_a()except RecursionError: print("construction cycle: neither can be first")def even(n): return True if n == 0 else odd(n - 1) # call cycle, but it endsdef odd(n): return False if n == 0 else even(n - 1)print("call cycle that ends:", even(10))A container looks for the first one
Three kinds and their cures
| Kind | You see | Interface helps? | Extraction helps? |
|---|---|---|---|
| Module cycle | Import error, half loaded module, headers that do not compile, packages that cannot be released alone | Yes, if it lives on the caller's side | Yes |
| Construction cycle | Container error, stack overflow in constructors, null field | No, the objects still need each other | Yes |
| Call cycle | Endless recursion, or a method entered again in the middle of a change | No | Often; or a rule that it must end |
Languages
How a module cycle hurts
| Language | What happens | Crutch |
|---|---|---|
| Python | from b import B meets a module that is only half run: ImportError. A plain import b survives if b is used later | Import inside the function; import for types only under TYPE_CHECKING |
| JavaScript, TypeScript | ES modules: reading a class before its module ran is a ReferenceError. CommonJS: you get an unfinished exports object | Import types only with import type |
| Java | Classes in a cycle compile. Static initializers that use each other can see unset values, and two threads can deadlock | None needed to compile, so cycles grow unseen |
| C++ | Headers that include each other: the second sees an incomplete type | Forward declaration, include in the .cpp, pimpl |
| Go | The compiler refuses import cycles between packages | None |
import pathlib, subprocess, sys, tempfiledef run(**files): with tempfile.TemporaryDirectory() as d: for name, text in files.items(): pathlib.Path(d, name + ".py").write_text(text) r = subprocess.run([sys.executable, "main.py"], cwd=d, capture_output=True, text=True) return (r.stdout or r.stderr).strip().splitlines()[-1][:88]main = "import order_service\nprint('started')"try: print(run(main=main, order_service="from customer_service import CustomerService\nclass OrderService: pass", customer_service="from order_service import OrderService\nclass CustomerService: pass")) print(run(main=main, order_service="from customer_service import CustomerService\nclass OrderService: pass", customer_service="class CustomerService:\n def f(self):\n from order_service import OrderService"))except OSError: print("this sandbox cannot start a second Python")# ImportError: cannot import name ... (most likely due to a circular import)# started// order_service.h#pragma once#include <vector>struct Order;class CustomerService; // forward declaration, no includeclass OrderService { CustomerService* customers_ = nullptr; // a pointer needs no full typepublic: void setCustomers(CustomerService* c); std::vector<Order> ordersOf(int customerId);};// order_service.cpp#include "order_service.h"#include "customer_service.h" // the full type, only herevoid OrderService::setCustomers(CustomerService* c) { customers_ = c; }// customer_service.h, with a hidden implementation (pimpl)#pragma once#include <memory>class CustomerService { struct Impl; std::unique_ptr<Impl> impl_; // the header includes nothing of orderspublic: CustomerService(); ~CustomerService(); // defined in the .cpp, where Impl is complete};Cures
Six ways out, and what each really removes
1. Invert with a port
The caller owns a small interface, the other side implements it. Removes the module cycle. See dependency inversion.
2. Inject later
A container makes both and connects them by setter. Both exist, but for a moment half done. The cycle stays.
3. Events
The first side announces a fact, the second listens. The arrow to the listener disappears. See Observer.
4. Extract a third class
What both want becomes its own class with no arrow back. Removes all three kinds. Try it first.
5. Mediator
A third object knows both and coordinates. The two no longer know each other. See Mediator.
6. Restructure packages
If two packages always change together, they may be one. Or layers must point one way.
The good shape: the missing third class
1/4The bottom
The directory only stores customers. It needs nobody, so it can be created first and tested alone.
usesimplements
Which cure?
Parent and child in a tree point at each other. Is that a cycle to remove?
BreaksSplit into two services
- How
- Parent service and child service with events between them.
- Limit
- One idea is cut in two, and each change crosses a border.
- Choose when
- Never for a small structure in one module.
WorksIds in place of references
- How
- The child keeps the id of its parent, and the tree looks it up.
- Limit
- Each step needs the tree.
- Choose when
- Saving to a database, immutable nodes.
StrongKeep it, inside one module
- How
- One class
Treeowns all nodes and keeps both arrows right. In C++ the arrow up is a raw or weak pointer. - Limit
- Both arrows must be changed in one method.
- Choose when
- Objects that live and die together. A cycle inside one small module is a data structure, not a design error.
Removes the cycle
- Extract the shared part
- Turn an arrow with a port (module cycle)
- Announce an event in place of a call
- Move a method to where its data is
- Merge what is truly one thing
Only hides it
- Import inside a function
- Setter or field injection
@Lazy,forwardRef- A global registry both sides ask
- More direct references
Summary
The whole topic in one minute.
Name the kind of cycle: module, construction or call. Interfaces cure the first, extraction cures all three, events turn a direct call into a notice.
Usually a cycle hides a third thing that both sides need, or a method that lives in the wrong class. Move it, and one arrow disappears or turns around.
Lazy imports, setters and forward references make a cycle start. They do not remove it. Keep cycles out with a check in the build.
- A cycle is a path of arrows back to the start, of any length.
- Three kinds: module, construction, call. Say which one before you choose a cure.
- Look for the third thing that both sides want. Extraction removes all three kinds.
- A port removes a module cycle, not a construction cycle.
- Lazy tricks start the program and keep the cycle.
- A check in the build keeps the graph free of cycles.
Sources
- Spring Boot 2.6 release notes
- Spring Framework: dependency injection, circular dependencies
- The Go language specification
- NestJS: circular dependency
- Angular: NG0200
- Python programming FAQ
- Python: graphlib
- Node.js: CommonJS modules, cycles
- ArchUnit user guide
- Import Linter
- Bazel: dependencies
- C++ Core Guidelines, SF.9
- cppreference: weak_ptr
- Java Language Specification 12.4: initialization
- Acyclic dependencies principle
- Tarjan's strongly connected components algorithm