Video in progress

Strong Middle 🧱 OOP and SOLID

If a circular dependency appears between classes or packages, how do you detect and break it?

A circular dependency is when A depends on B and B depends on A. Such modules can't be understood, tested or split apart on their own. You break it by moving the interface to the side that uses it, extracting the shared part into a third module, or using events.

📖 Answer

Since Spring Boot 2.6, a bean cycle with constructor injection fails at startup by default (The dependencies of some of the beans form a cycle). Many people "fix" it with spring.main.allow-circular-references=true or @Lazy, which hides the symptom while the design problem stays.

Detecting cycles at the package level:

  • ArchUnit: slices().matching("com.app.(*)..").should().beFreeOfCycles();
  • IntelliJ: Analyze → Dependency Matrix;
  • jdeps, or splitting into Gradle/Maven modules, where the compiler doesn't allow a cycle.

Ways to break it:

  1. Dependency inversion. order → user and user → order (to check the orders when a user is deleted). Declare a UserDeletionGuard interface in the user package and have order implement it. Now there is only order → user.

  2. An event. UserService publishes a UserDeleted event, and the order module subscribes to it.

  3. Extracting the shared part. Move types both use, like Money and UserId, into a shared-kernel.

  4. Rethinking responsibilities. Often a cycle means one class is doing the work of two modules, and it should be split.

A cycle at the class level (two services call each other) usually shows that a third, higher-level orchestrator is missing: let CheckoutService call both, and they won't know about each other.