Why should you use an addiction injection

Corner coding

Let’s look at the same thing. Building an electronic trading application is quite common. Whether it is an online site or a physical point sales system, the application will need to process credit cards. Now the processing of credit cards is quite a difficult thing, but it is something that fits abstractions.

Let’s say your system will use the Paystuff Payssor processor. If you are strict to the Yagni principle (which I would recommend) then you just go forward and make a hard encoding Countrytuff’s implementation so:


class PayStuffPaymentProcessor {
  processPayment(amount: number) {
    console.log(`Processing $${amount} payment via PayStuff...`);
  }
}

class Checkout {
  private paymentProcessor: PayStuffPaymentProcessor;

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

  processOrder(amount: number) {
    this.paymentProcessor.processPayment(amount);
    console.log("Order processed successfully!");
  }
}

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

I think this great works. You can process and collect money on orders and everything is fine. It’s not changing. And it doesn’t matter that you can’t try it at all. But hey, you won’t need anything more, right? Yagni for victory!

But oops! The country is moving from business! Instead of paystuff you must start using the Connectbucks processor. And on the same day you realize that your product manager asks you to add support for payments with PayPal and Google Pay. Suddenly your system is not only difficult to test, but it doesn’t even work, and the delivery of all these new features will require your system for your system, right?

Abstraction saves the day

Instead, you should do, it is to realize that you need abstraction. So you create an interface and write all the code against it and not a specific implementation. Then, intensely creating the execution on the spot, postpone the decision to implement and “put” in the constructor you want to use for the first time.

Leave a Comment