Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs Circular dependency forwardRef() drawbacks

Official Circular dependency says:

A circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers.

While circular dependencies should be avoided where possible, you can't always do so.

What are the reasons for not using forwardRef()?

like image 947
Jasurbek Nabijonov Avatar asked Jan 11 '21 17:01

Jasurbek Nabijonov


People also ask

What's wrong with circular dependencies?

Cyclic dependencies between components inhibit understanding, testing, and reuse (you need to understand both components to use either). This makes the system less maintainable because understanding the code is harder. Lack of understanding makes changes harder and more error-prone.

How does NestJS resolve circular dependency?

Avoiding circular dependencies by refactoring The NestJS documentation advises that circular dependencies be avoided where possible. Circular dependencies create tight couplings between the classes or modules involved, which means both classes or modules have to be recompiled every time either of them is changed.

What is forwardRef in NestJS?

Forward reference A forward reference allows Nest to reference classes which aren't yet defined using the forwardRef() utility function. For example, if CatsService and CommonService depend on each other, both sides of the relationship can use @Inject() and the forwardRef() utility to resolve the circular dependency.

Are circular dependencies OK?

and, yes, cyclic dependencies are bad: They cause programs to include unnecessary functionality because things are dragged in which aren't needed. They make it a lot harder to test software. They make it a lot harder to reason about software.


1 Answers

Circular dependencies usually mean you have tightly bound logic and possibly unstable architecture that will not allow you to scale. If you really don't want to care about that, you can just sprinkle in forwardRef wherever you want, constructors and services, but that could lead to some strange, hard to resolve errors, and is generally seen as a bad practice amongst the Nest community.

like image 196
Jay McDoniel Avatar answered Sep 23 '22 15:09

Jay McDoniel