What are the drawbacks of introducing a dependency within the constructor?

I'm struggling to understand why breaking the rules is considered bad.

   import {DepClass} from './di-import' // <- some dependency imports here

   class DI1 {
     dep1: DepClass
     constructor(){
       this.dep1 = new DepClass() // <- not ideal
     }
     ...... 
     }

    class DI2 {
      dep2: DepClass
      constructor(d: DepClass){     // <- slightly better
        this.dep2 = d
      }
      ......
    }

So, I know that a class shouldn't create instances of its dependencies on its own as it breaks the IoC rule. But what are the negative consequences of this? What overhead occurs?

What is the difference between directly creating an instance of Dependency in the constructor and passing a copy of an already existing Dependency into the constructor as an argument? Other than both classes functioning correctly.

I have one thought though. Perhaps all of this is necessary for the proper functioning of the DI container, which carefully inspects constructor arguments.

Thanks in advance.

Answer №1

function initiate(){
  this.dependency1 = new DependencyClass() // <- not ideal
}

When you create an instance of the dependent class, a new object of DependencyClass is also created.


function initialize(dep: DependencyClass){     // <- better approach
  this.dependency2 = dep
}

In this scenario, a single DependencyClass instance is provided by the dependency injection framework and shared among classes that require it.


If multiple classes rely on DependencyClass, the first method would lead to multiple instances being created for each object instantiation.

In contrast, with the second method, only one instance of DependencyClass is created and shared across all classes that specify it as a dependency.

Initially, dependency injection may not seem necessary in small examples like this. However, as your application grows and numerous classes have various dependencies, maintaining clean code becomes essential.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The preflight request in Angular2 is being rejected due to failing the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header

I encountered an issue while attempting to execute a basic POST request to establish an account using an API in .NET. The process fails with the mentioned warning title. Interestingly, performing the same request in Postman (an API testing tool) yields a s ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

What is the best way to implement a timer using hooks in React?

Just getting started with React! I began my journey last week ;) My first task is to build a timer that includes a reset feature and can count seconds. While the reset function is functioning properly, the timer isn't. Can anyone suggest the best ap ...

Guidelines for transmitting form information to a web API using Angular

I am currently working on an Angular 6 project where I have a form and a table that retrieves data from a web API. I want to know if it's possible to send the form data to that web API. Here is the code snippet that I have so far: HTML Form: &l ...

The error in Angular 6 is that the property 'controls' is not available on the type 'AbstractControl'

What happens when we use setvalue in a for loop? Everything seems to be running smoothly, but unfortunately an error is thrown: The property 'controls' is not recognized on the type 'AbstractControl'. In Angular 6, how can we resol ...

Self-referencing type alias creates a circular reference

What causes the discrepancy between these two examples? type Foo = { x: Foo } and this: type Bar<A> = { x: A } type Foo = Bar<Foo> // ^^^ Type alias 'Foo' circularly references itself Aren't they supposed to have the same o ...

How can TypeScript generics be used to create multiple indexes?

Here is an interface snippet: interface A { a1: { a11: string }; a2: { a21: string }; a3: { a31: string }; } I am looking to create a generic type object with indexing based on selected fields from interface A. Here is the pseudo-code exampl ...

Error Type: Jest: A transform is required to have a `process` function in order for it to

Encountering an error while running 'npm test': FAIL __tests__/unit/domain/services/demo-service.ts ● Test suite failed to run TypeError: Jest: a transform must export a `process` function. at ScriptTransformer._getTransformer ( ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Manually Enroll Node Module

Question: I am tackling a challenge in my TypeScript project where I need to interact with multiple APIs that are not available locally on my computer, but exist on the web. The code compiles without issues on my local machine as I have all the API declar ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

`How can I effectively test a React.js page utilizing both Context and useEffect?`

I'm struggling with testing a page that uses Context and useEffect with Jest and Testing-library, can you offer any assistance? REPOSITORY: https://github.com/jefferson1104/padawan Context File: src/context/personContext.tsx import { createContext, ...

Leveraging Component without the need for Import

Is it possible to use a component without re-importing it if it's already declared in AppModule? With 10 or more pages/components to manage, importing each one can be challenging. Here is my app.module.ts import { NgModule, ErrorHandler } from &apos ...

Vuex - Managing dependencies within nested modules

I am facing a challenge in expressing a dependency between properties within my app's state using Vuex. Upon logging in, the user must select one of several workspaces to connect to. It is essential for the workspace to depend on the login status; ho ...

Challenges encountered when assigning values in a form with Material UI, Formik, and Typescript

When attempting to set the 'role' and 'active' values on a form, I encountered a couple of issues. The first problem arises from the fact that the selectors' original values are not being properly set. These values are fetched in ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...