Imagine something that can be changed at runtime and is already been used and has to be replicated again.
Think of an e-comm app like Amazon where you can choose from different Payment methods -> Cash, Card (Credit Card, Debit Card), UPI, etc... Now if you want to buy a Prime membership wouldn't you expect all these Payment methods there too??
Let's look at how such a thing is actually carried and scaled out.
This is your ShoppingCart
class ShoppingCart {
public void checkout(String paymentType, int amount) {
if (paymentType.equals("CREDIT")) {
System.out.println("Paid " + amount + " with Credit Card");
} else if (paymentType.equals("PAYPAL")) {
System.out.println("Paid " + amount + " with PayPal");
} else if (paymentType.equals("UPI")) {
System.out.println("Paid " + amount + " with UPI");
}
}
}
And this is your Subscription
class Subscription {
public void checkout(String paymentType, int amount) {
if (paymentType.equals("CREDIT")) {
System.out.println("Paid " + amount + " with Credit Card");
} else if (paymentType.equals("PAYPAL")) {
System.out.println("Paid " + amount + " with PayPal");
} else if (paymentType.equals("UPI")) {
System.out.println("Paid " + amount + " with UPI");
}
}
}
Don't they look the same!!
Now imagine if you want to add a new method "Cash" for both of them. Yes you are right!! This is a classic example of Code Redundancy
We could have instead did something like this
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " with Credit Card");
}
}
class PayPalPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " with PayPal");
}
}
class UpiPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " with UPI");
}
}
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
class Subscription {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
The code is now
- More convenient.
- More scalable.
- Easily maintainable.
- No redundancy.
- More reliable
Top comments (0)