Tired of Nested if-else? ??- Strategy Pattern??can save you here
Priyabrata Naskar
SDE @Zomato | Founding Android Engineer @Semaai l Android Developer | Kotlin | Jetpack Compose | Coroutines | Open Source | CIS Hackathon 2021 ?? | Let's Build Together ??
Today, while going through the codebase I???? observed something in the production code.
private?fun?placeOrder()?{
????if?(paymentMethod?.isCOD?==?true)?{
????????...
????????...
????}?else?if?(
????????paymentMethod?.paymentType?==?PAYMENT_TYPE_ONLINE
????)?{
????????...
????????...
????}?else?if?(paymentMethod?.paymentType?==?PAYMENT_TYPE_BNPL)?{
????????...
????????...
????}
}
For the first time if you see this code it'll look ?? fine. But once more and more payment method comes in you'll find it difficult ?? to manage the code. So how to make this more scalable?
The answer is Strategy Design Pattern
First we'll create an interface: PaymentStrategy??
interface PaymentStrategy {
fun placeOrder(order: OrderRequest)
}
Now, we'll be creating 3 Concrete Classes:
class?CODPaymentStrategy?:?PaymentStrategy?
????override?fun?placeOrder(order:?OrderRequest)?{
????????...
...
????}
}
class?OnlinePaymentStrategy?:?PaymentStrategy?{
????override?fun?placeOrder(order:?OrderRequest)?{
????????...
...
????}
}
class?BNPLPaymentStrategy?:?PaymentStrategy?{
????override?fun?placeOrder(order:?OrderRequest)?{
...
...
}
}
Now, need to create a PaymentContext class:
class PaymentContext(private val strategy: PaymentStrategy)
fun executeStrategy(orderRequest: OrderRequest) {
strategy.execute(orderRequest)
}
}
Finally, we can use this PaymentContext class??:
val paymentContext = when {
? ? paymentMethod?.isCOD?==?true -> PaymentContext(CODPaymentStrategy())
? ? paymentMethod?.paymentType== ONLINE_Payment -> PaymentContext(VirtualPaymentStrategy())
? ? paymentMethod?.paymentType?==?PAYMENT_TYPE_BNPL -> PaymentContext(BNPLPaymentStrategy())
}
paymentContext.executeStrategy(orderRequest)
That's it for now! I'm an Android Engineer and I do share knowledge on the same. Feel free to follow me Priyabrata Naskar ????
SDE-I @Groww ? Ex- OkCredit ? Android Developer (Kotlin) ? MVVM ? MVI ? Android Jetpack
1 年The example of a production codebase is just lit ??