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. 

Leave a Reply