Bug's Package Fail ๐ฆ๐ฟ When Dependency Injection Goes Wrong #shorts
Video: Bug's Package Fail ๐ฆ๐ฟ When Dependency Injection Goes Wrong #shorts by Taught by Celeste AI - AI Coding Coach
Watch full page โBug's Package Fail: When Dependency Injection Goes Wrong
Dependency Injection (DI) is a powerful technique to manage dependencies in your code, but injecting the wrong dependency can lead to unexpected behaviorโlike receiving cat food instead of headphones! This example demonstrates how a simple mix-up in DI can cause bugs and how to avoid them.
Code
// Define an interface for a product
interface Product {
getDescription(): string;
}
// Correct dependency: Headphones implementation
class Headphones implements Product {
getDescription(): string {
return "High-quality headphones ๐ง";
}
}
// Wrong dependency: CatFood implementation
class CatFood implements Product {
getDescription(): string {
return "Delicious cat food ๐ฑ";
}
}
// Consumer class that depends on Product
class Order {
private product: Product;
// Dependency Injection via constructor
constructor(product: Product) {
this.product = product;
}
deliver() {
console.log("Delivering: " + this.product.getDescription());
}
}
// Injecting the correct dependency
const correctOrder = new Order(new Headphones());
correctOrder.deliver(); // Output: Delivering: High-quality headphones ๐ง
// Injecting the wrong dependency by mistake
const wrongOrder = new Order(new CatFood());
wrongOrder.deliver(); // Output: Delivering: Delicious cat food ๐ฑ
Key Points
- Dependency Injection allows flexible swapping of components without changing the consumer code.
- Injecting the wrong dependency can cause unexpected and incorrect behavior in your application.
- Use clear interfaces and strong typing to minimize the risk of injecting incorrect dependencies.
- Unit tests can help catch issues caused by wrong dependencies early in development.
- Always verify that the injected dependency matches the expected contract or interface.