10.9 C
New York
Thursday, March 6, 2025

Why it is best to use dependency injection



Coding your self right into a nook

Let’s have a look at an instance. Constructing an e-commerce utility is kind of commonplace. Whether or not it’s a web based web site or a bodily point-of-sale system, the app might want to course of bank cards. Now, bank card processing is a reasonably complicated factor, however it’s one thing that lends itself to abstractions. 

Let’s say your system shall be utilizing the PayStuff cost processor. In case you are a strict adherent to the YAGNI precept (which I wouldn’t advocate) then you definitely’ll simply go forward and hard-code the implementation of PayStuff like so:


class PayStuffPaymentProcessor {
  processPayment(quantity: quantity) {
    console.log(`Processing $${quantity} cost through PayStuff...`);
  }
}

class Checkout {
  personal paymentProcessor: PayStuffPaymentProcessor;

  constructor() {
    this.paymentProcessor = new PayStuffPaymentProcessor();
  }

  processOrder(quantity: quantity) {
    this.paymentProcessor.processPayment(quantity);
    console.log("Order processed efficiently!");
  }
}

// Utilization
const checkout = new Checkout();
checkout.processOrder(100);
checkout.processOrder(50);

This works high quality, I suppose. You’ll be able to course of and gather cash for orders and all is nicely. It’s not changeable. And by no means thoughts which you can’t unit take a look at it in any respect. However hey, you aren’t going to wish something extra, proper? YAGNI for the win!

However oops! PayStuff goes out of enterprise! You could begin utilizing the ConnectBucks processor as a substitute of PayStuff. And the exact same day you notice that, your product supervisor asks you so as to add assist for paying with PayPal and Google Pay. All of the sudden, your system shouldn’t be solely laborious to check, nevertheless it doesn’t even work anymore, and supplying all this new performance would require some fairly main surgical procedure to your system, proper?

Abstraction saves the day

What it is best to have finished as a substitute is notice that you will want an abstraction. Thus, you create an interface and write all of your code in opposition to it and never a particular implementation. Then, as a substitute of making the implementation on the spot, you defer the implementation resolution and “inject” into the constructor the implementation of the abstraction that you just wish to use.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles