Reputation: 4337
the book "Clean Architecture" said:
When using dynamically typed languages like Ruby and Python ... dependency inversion does not require either the declaration or the inheritance of interfaces.
but I don't quite understand it, the book didn't provide any example
my understanding of the DIP is that if ClassA depends on ClassB violating the DIP, we can introduce an InterfaceC, then we get something like
ClassA ---> InterfaceC <--- ClassB
I've also looked at some examples on the internet, like this one that attempts dependency injection between PurchaseHandler
and PayPal
, https://duncan-mcardle.medium.com/solid-principle-5-dependency-inversion-javascript-7b054685f7cb
class PurchaseHandler {
processPayment(paymentDetails, amount) {
const paymentSuccess = PaymentHandler.requestPayment(
paymentDetails,
amount
);
if (paymentSuccess) {
// Do something
return true;
}
// Do something
return false;
}
}
class PaymentHandler {
requestPayment(paymentDetails, amount) {
// Complicated, PayPal specific logic goes here
return PayPal.requestPayment(paymentDetails, amount);
}
}
However, it seems to simply add a layer between them, resulting in this dependency graph:
PurchaseHandler ---> PaymentHandler ---> PayPal
no inversion is happening here...
=== update Mar 15th, 2024 === it's true that the above example doesn't work because of the language syntax...
finally, I got the answer from this youtube video https://www.youtube.com/watch?v=9oHY5TllWaU
in js, it's similar to the Facade design pattern
Upvotes: 0
Views: 97
Reputation: 1
You must have in mind that interfaces are not supported in JavaScript. The point of interfaces in clean architecture is that the Class A must depend on a method from Class B but it does not matter how the method is implemented. This allows you to make changes on Class B without affecting Class A. The interface only ensures that the method from Class B exists not the way it is implemented.
In your example, the class PurchaseHandler depends on a Class PaymentHandler but it doesn't matter if you use PayPal or another payment method. You can change the payment method with out rewriting the class PurchaseHandler. This way, the Dependency inversion principle is accomplished.
If you want to do it in a more pure way in javascript, you should use inheritance:
PurchaseHandler -> PaymentHandler_Child <- PaymentHandler_Parent
The class PaymentHandler_Parent must have a method requestPayment but must return an error or something else unexpected. Then using inheritance, you must implement in class PaymentHandler_Child the payment in a method called requestPayment. In this way, you are obliged to implement this method as if it were an interface in another programing language. The class PurchaseHandler, must call the method implemented in PaymentHandler_Child.
Upvotes: 0