Marcio Cunha

What is Dependency Injection? How to use it in your code

Learn how dependency injection decouples systems and simplifies testing. Stop creating objects internally and gain flexibility in your backend code.

Marcio Cunha•3 min
Also available in:PortuguêsEspañol
Summary
  • Dependency injection removes the responsibility of creating objects from the classes that use them.
  • Decoupling allows for swapping implementations easily, like replacing a real database with a mock for tests.
  • Excessive direct instantiation using the new operator creates rigid dependencies that are hard to maintain.
  • Inversion of Control is the architectural principle that serves as the theoretical base for this pattern.
  • Implementing this pattern improves code readability and allows the application to evolve without constant breakages.

The problem with hardcoded dependencies

Imagine building a coffee machine. If the machine is manufactured with a built-in coffee grinder soldered inside, you can never replace it with a better one without destroying the unit. In software engineering, we do this constantly when we write code like this.service = new EmailService(); inside a class. This creates a direct, rigid dependency: your class now 'knows' and 'owns' the email service.

When a class is responsible for creating its own dependencies, it becomes difficult to test and almost impossible to configure differently. If you want to test the email sending process without firing real emails to customers, you would be stuck with the original code. This is what we call coupled code, where parts are glued together as if they were a single unit.

Understanding Dependency Injection

Dependency injection, or DI, is the act of passing the required objects into a class (the dependencies) via constructor or parameters, instead of letting the class fetch or create them itself. Returning to our analogy, it's like creating a coffee machine with a standard mount where you can snap in any grinder that follows that standard. The machine doesn't need to know how the grinder works, only how to use it.

In practice, this means you provide what the class needs to function. If it needs a database to save users, you inject a functional connection the moment the class is instantiated. This separates who creates the object from who uses it. It is a fundamental concept for building robust systems, avoiding bottlenecks that occur in poorly structured code, much like when you need to investigate why a slow database with heavy queries in PostgreSQL brings down your app due to a lack of service layer isolation.

Applying DI in your backend

To implement it, the first step is defining contracts, usually through interfaces. The interface ensures that, regardless of the concrete implementation, the sending service will have a method called send(). Thus, your main class accepts any object that implements that interface. Below is an example of this decoupling in a typical structure:

// Before: Coupled
class UsuarioService {
  constructor() {
    this.db = new PostgresDatabase(); // Fixed dependency
  }
}

// After: Injected
class UsuarioService {
  constructor(db) {
    this.db = db; // Injected dependency
  }
}

By doing this, when running the application, you inject the real database. When running unit tests, you inject a mock object that doesn't touch the real database. This solves infrastructure problems quickly, allowing you to focus on logic. If you have ever faced build errors, like a broken NPM cache that requires cleaning, you know how clarity and separation of concerns help maintenance.

Real benefits of a decoupled architecture

The main advantage is the ease of change. If tomorrow your system decides to switch from Postgres to MongoDB, you don't need to change a single line of the UsuarioService class, provided the new database obeys the expected interface. This drastically reduces the chance of introducing bugs during refactoring, a common headache in legacy systems.

Furthermore, testability increases exponentially. Since you can inject any version of a component, you can create intentional error scenarios to test how your application reacts, without depending on the real system state. This is what allows engineers to have more confidence when implementing fixes for CORS errors in APIs with a Reverse Proxy, as the business logic remains isolated from the network and persistence layers.

Conclusion

Dependency injection isn't about adding complexity, but about bringing order to the chaos that arises in systems that grow without a clear design. Although it requires an initial learning curve, the return in terms of maintainability and agility to evolve the backend is immense.

Start by applying the pattern in smaller classes and see how unit testing becomes simpler. Over time, using Inversion of Control containers will make managing these dependencies even easier in larger projects, ensuring clean, testable, and, above all, professional code.