Home > Web Front-end > JS Tutorial > Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

Linda Hamilton
Release: 2024-11-30 00:25:11
Original
280 people have browsed it

If you're familiar with object-oriented programming, or are just starting to explore it, you've likely encountered the acronym SOLID. SOLID represents a set of principles designed to help developers write clean, maintainable, and scalable code. In this article, we will focus on the "D" in SOLID, which stands for the Dependency Inversion Principle.

But before diving into the details, let's first take a moment to understand the "why" behind these principles.

In object-oriented programming, we typically break down our applications into classes, each encapsulating specific business logic and interacting with other classes. For instance, imagine a simple online store where users can add products to their shopping cart. This scenario could be modeled with several classes working together to manage the store’s operations. Let's consider this example as a foundation to explore how the Dependency Inversion Principle can improve the design of our system.

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor() {
   this.productService = new ProductService();
 }

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor() {
   this.orderService = new OrderService();
 }

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}
Copy after login
Copy after login
Copy after login
Copy after login

As we can see, dependencies like OrderService and ProductService are tightly coupled within the class constructor. This direct dependency makes it difficult to replace or mock these components, which poses a challenge when it comes to testing or swapping implementations.

Dependency Injection (DI)

The Dependency Injection (DI) pattern offers a solution to this problem. By following the DI pattern, we can decouple these dependencies and make our code more flexible and testable. Here’s how we can refactor the code to implement DI:

Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor(private productService: ProductService) {}

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor(private orderService: OrderService) {}

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}


new UserService(new OrderService(new ProductService()));
Copy after login
Copy after login
Copy after login

We’re explicitly passing dependencies to the constructor of each service, which, while a step in the right direction, still results in tightly coupled classes. This approach does improve flexibility slightly, but it doesn’t fully address the underlying issue of making our code more modular and easily testable.

Dependency Inversion Principle (DiP)

The Dependency Inversion Principle (DiP) takes this a step further by answering the crucial question: What should we pass? The principle suggests that instead of passing concrete implementations, we should pass only the necessary abstractions—specifically, dependencies that match the expected interface.

For example, consider the ProductService class with a getProducts method that returns an array of products. Instead of directly coupling ProductService to a specific implementation (e.g., fetching data from a database), we could implement it in various ways. One implementation might fetch products from a database, while another might return a hardcoded JSON object for testing. The key is that both implementations share the same interface, ensuring flexibility and interchangeability.

Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

Inversion of Control (IoC) and Service Locator

To put this principle into practice, we often rely on a pattern called Inversion of Control (IoC). IoC is a technique where the control over the creation and management of dependencies is transferred from the class itself to an external component. This is typically implemented through a Dependency Injection container or a Service Locator, which acts as a registry from which we can request the required dependencies. With IoC, we can dynamically inject the appropriate dependencies without hardcoding them into the class constructors, making the system more modular and easier to maintain.

Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor() {
   this.productService = new ProductService();
 }

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor() {
   this.orderService = new OrderService();
 }

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}
Copy after login
Copy after login
Copy after login
Copy after login

As we can see, dependencies are registered within the container, which allows them to be replaced or swapped when necessary. This flexibility is a key advantage, as it promotes loose coupling between components.

However, this approach has some downsides. Since dependencies are resolved at runtime, it can lead to runtime errors if something goes wrong (e.g., if a dependency is missing or incompatible). Furthermore, there is no guarantee that the registered dependency will strictly conform to the expected interface, which can cause subtle issues. This method of dependency resolution is often referred to as the Service Locator pattern, and it is considered an anti-pattern in many cases due to its reliance on runtime resolution and its potential to obscure dependencies.

InversifyJS

One of the most popular libraries in JavaScript for implementing the Inversion of Control (IoC) pattern is InversifyJS. It provides a robust and flexible framework for managing dependencies in a clean, modular way. However, InversifyJS has some drawbacks. One major limitation is the amount of boilerplate code required to set up and manage dependencies. Additionally, it often requires structuring your application in a specific way, which may not suit every project.

Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

An alternative to InversifyJS is Friendly-DI, a lightweight and more streamlined approach for managing dependencies in JavaScript and TypeScript applications. It is inspired by the DI systems in frameworks like Angular and NestJS but is designed to be more minimal and less verbose.

Some key advantages of Friendly-DI include:

  • Small size: Just 2 KB with no external dependencies.
  • Cross-platform: Works seamlessly in both the browser and Node.js environments.
  • Simple API: Intuitive and easy to use, with minimal configuration.
  • MIT License: Open-source with permissive licensing.

However, it's important to note that Friendly-DI is designed specifically for TypeScript, and you'll need to install its dependencies before you can start using it.

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor() {
   this.productService = new ProductService();
 }

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor() {
   this.orderService = new OrderService();
 }

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}
Copy after login
Copy after login
Copy after login
Copy after login

And also extend tsconfig.json:

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor(private productService: ProductService) {}

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor(private orderService: OrderService) {}

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}


new UserService(new OrderService(new ProductService()));
Copy after login
Copy after login
Copy after login

The example above can be modified with Friendly-DI:

class ServiceLocator {
 static #modules = new Map();

 static get(moduleName: string) {
   return ServiceLocator.#modules.get(moduleName);
 }

 static set(moduleName: string, exp: never) {
   ServiceLocator.#modules.set(moduleName, exp);
 }
}

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor() {
   const ProductService = ServiceLocator.get('ProductService');
   this.productService = new ProductService();
 }

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor() {
   const OrderService = ServiceLocator.get('OrderService');
   this.orderService = new OrderService();
 }

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}

ServiceLocator.set('ProductService', ProductService);
ServiceLocator.set('OrderService', OrderService);


new UserService();
Copy after login
Copy after login
  1. As we can see, we've added the @Injectable() decorator, which marks our classes as injectable, signaling that they are part of the dependency injection system. This decorator allows the DI container to know that these classes can be instantiated and injected where needed.

  2. When declaring a class as a dependency in a constructor, we don’t directly bind to the concrete class itself. Instead, we define the dependency in terms of its interface. This decouples our code from the specific implementation and allows for greater flexibility, making it easier to swap or mock dependencies when needed.

  3. In this example, we placed our UserService in the App class. This pattern is known as the Composition Root. The Composition Root is the central place in the application where all dependencies are assembled and injected — essentially the "root" of our application's dependency graph. By keeping this logic in one place, we maintain better control over how dependencies are resolved and injected throughout the app.

The final step is to register the App class in the DI Container, which will enable the container to manage the lifecycle and injection of all dependencies when the application starts.

Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

npm i friendly-di reflect-metadata
Copy after login

If we need to replace any classes in our application we just need to create mock-class following the origin interface:

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor() {
   this.productService = new ProductService();
 }

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor() {
   this.orderService = new OrderService();
 }

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}
Copy after login
Copy after login
Copy after login
Copy after login

and then use replace method where we declare replaceable class to mock class:

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor(private productService: ProductService) {}

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor(private orderService: OrderService) {}

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}


new UserService(new OrderService(new ProductService()));
Copy after login
Copy after login
Copy after login

Friendly-DI we can make replace many times:

class ServiceLocator {
 static #modules = new Map();

 static get(moduleName: string) {
   return ServiceLocator.#modules.get(moduleName);
 }

 static set(moduleName: string, exp: never) {
   ServiceLocator.#modules.set(moduleName, exp);
 }
}

class ProductService {
 getProducts() {
   return ['product 1', 'product 2', 'product 3'];
 }
}


class OrderService {
 constructor() {
   const ProductService = ServiceLocator.get('ProductService');
   this.productService = new ProductService();
 }

 getOrdersForUser() {
   return this.productService.getProducts();
 }
}


class UserService {
 constructor() {
   const OrderService = ServiceLocator.get('OrderService');
   this.orderService = new OrderService();
 }

 getUserOrders() {
   return this.orderService.getOrdersForUser();
 }
}

ServiceLocator.set('ProductService', ProductService);
ServiceLocator.set('OrderService', OrderService);


new UserService();
Copy after login
Copy after login

That's all, if you have any comments or clarifications on this topic, please write your thoughts in the comments.

The above is the detailed content of Mastering the Dependency Inversion Principle: Best Practices for Clean Code with DI. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template