“Cuando tienes 20 años, te importa lo que todos piensan de ti, cuando tienes 40 años dejas de preocuparte por lo que todos piensan, cuando tienes 60 años, te das cuenta de que nadie estaba pensando en ti en primer lugar”

Winston Churchill

Dependency Inversion Principle (DIP) and WooCommerce

Today I was reading about DIP, which made me think a lot about how I write software.

Let start by defining what Dependency Inversion Principle. Uncle Bob, in his book Clean Architecture, says:

The Dependency Inversion Principle (DIP) tells us that the most flexible systems are those in which source code dependencies refer only to abstractions, not concretions.

Let’s picture this with a code example:

This is a simple function that accepts two parameters, but based on the DIP principle, there’s a problem with this simple function. Can you see it? It takes WC_Gateway_GreenPay, which is the class of a unique payment gateway; what if the site changes the payment gateway to Cash On Delivery, then we’ll need to update our function to:

Now imagine you have many examples likes these that force you to update your code; this is not very flexible; instead, let’s follow the DIP principle and make it adjustable by depending on the abstract class WC_Payment_Gateway:

If the site switches to another payment method or implements multiple, we won’t have to worry about our code not being compatible.

The DIP principle helps us avoid bugs and spend time fixing them in the future, makes our code flexible and without sacrificing anything.