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

Nov 30, 2024 am 12:25 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles