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

Take the quiz on the full lesson page
Test what you've read Β· interactive walkthrough
β†’

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.
Ready? Take the quiz on the full lesson page β†’
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.
β†’