Back to Blog

Bug's Package Fail ๐Ÿ“ฆ๐Ÿ˜ฟ When Dependency Injection Goes Wrong #shorts

Sandy LaneSandy Lane
โ€ข

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.