Tired of Nested if-else? ??- Strategy Pattern??can save you here

Tired of Nested if-else? ??- Strategy Pattern??can save you here

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 ????

Utkarsh Saxena

SDE-I @Groww ? Ex- OkCredit ? Android Developer (Kotlin) ? MVVM ? MVI ? Android Jetpack

1 年

The example of a production codebase is just lit ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了