Dependency Inversion Principle

1 min read
The Dependency Inversion Principle (DIP) states that high level modules(Payment ) should not depend on low level modules(UpiPayment ,CryptoPayment); both should depend on abstractions(PaymentGateway). Abstractions should not depend on details.
Bad Practice - Principle not followed
public class Payment {
public void processPayment(UpiPayment upiPayment) {
// Implementation for processing UPI payment
}
}
class UpiPayment {
// UPI payment related properties and methods
}
Tomm you want to add CryptoPayment you need to modify the Payment class this bad .
Good Practice - Principle followed
public class Payment {
public void processPayment(PaymentGateway paymentGateway) {
// Implementation for processing payment via PaymentGateway
}
}
interface PaymentGateway {
// Payment gateway related methods
}
class UpiPayment implements PaymentGateway {
// UPI payment related properties and methods
}
class CryptoPayment implements PaymentGateway {
// Cryptocurrency payment related properties and methods
}
0
Subscribe to my newsletter
Read articles from Palanivel SundaraRajan GugaGuruNathan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Palanivel SundaraRajan GugaGuruNathan
Palanivel SundaraRajan GugaGuruNathan
Hi , thanks for stopping by! I am full-stack developer and I'm passionate about making complex concepts clear through code and visuals. After all, a picture (and a code snippet) is worth a thousand words! I hope you enjoy my blog.