search
HomeWeb Front-endJS TutorialMastering the Dependency Inversion Principle: Best Practices for Clean Code with DI

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();
 }
}

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()));

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();
 }
}

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();
 }
}

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()));

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();
  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

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();
 }
}

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()));

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();

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
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.