Inicio Information Technology Why you must use dependency injection

Why you must use dependency injection

0
Why you must 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 will likely be utilizing the PayStuff fee processor. If you’re a strict adherent to the YAGNI precept (which I wouldn’t recommend) 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} fee 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 nice, I suppose. You possibly can course of and accumulate cash for orders and all is nicely. It’s not changeable. And by no means thoughts that you could’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! It is advisable to begin utilizing the ConnectBucks processor as a substitute of PayStuff. And the exact same day you understand that, your product supervisor asks you so as to add assist for paying with PayPal and Google Pay. All of the sudden, your system just isn’t solely onerous to check, however 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 you must have carried out as a substitute is understand that you will want an abstraction. Thus, you create an interface and write all of your code in opposition to it and never a selected implementation. Then, as a substitute of making the implementation on the spot, you defer the implementation choice and “inject” into the constructor the implementation of the abstraction that you just wish to use.

DEJA UNA RESPUESTA

Por favor ingrese su comentario!
Por favor ingrese su nombre aquí