Learn extra at:
Coding your self right into a nook
Let’s take a look at an instance. Constructing an e-commerce utility is sort of commonplace. Whether or not it’s an internet 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 might be utilizing the PayStuff cost 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} cost by way of 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 superb, I assume. You’ll be able to course of and accumulate cash for orders and all is effectively. It’s not changeable. And by no means thoughts you can’t unit check it in any respect. However hey, you aren’t going to want something extra, proper? YAGNI for the win!
However oops! PayStuff goes out of enterprise! It’s good to begin utilizing the ConnectBucks processor as an alternative of PayStuff. And the exact same day you notice that, your product supervisor asks you so as to add help for paying with PayPal and Google Pay. Instantly, your system is just not solely arduous 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 executed as an alternative is notice that you’re going to 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 an alternative of making the implementation on the spot, you defer the implementation determination and “inject” into the constructor the implementation of the abstraction that you simply need to use.