Skip to content

Open Closed principle

Devrath edited this page Dec 31, 2023 · 9 revisions
π™²π™Ύπ™½πšƒπ™΄π™½πšƒπš‚
What is Open Closed Principle ?
Code
Structure
How open/closed principle is used here

What is Open Closed Principle ?

A class must be open for extension and closed for modification

Code

Payment.kt

interface Payment {
    fun processPayment(int : Int) : String
}

CreditCard.kt

class CreditCard : Payment {
    override fun processPayment(int: Int): String {
        // Logic for processing the payment of credit card
        return "Result of acknowledgement"
    }

}

DebitCard.kt

class DebitCard : Payment {
    override fun processPayment(int: Int): String {
        // Logic for processing the payment of debit card
        return "Result of acknowledgement"
    }

}

PaymentProcessor.kt

class PaymentProcessor {

    private val paymentMethods : MutableList<Payment> = arrayListOf()

    /**
     * Add a new payment method
     */
    fun addPaymentMethod(payment : Payment){
        paymentMethods.add(payment)
    }

    /**
     * Process the payment
     */
    fun processPayment(amount : Int){

        for (payment in paymentMethods){
            val result = payment.processPayment(amount);
            println(result)
        }

    }

}

Demo

   fun demo() {
        // Amount to pay
        val amountToPay = 100

        // We shall assume that we are paying via credit card
        val creditCardPayment = CreditCard()
        // Payment processor is used to process the payments
        val paymentProcessor = PaymentProcessor()

        // Add the payment method
        paymentProcessor.addPaymentMethod(creditCardPayment)
        // Process the payment
        paymentProcessor.processPayment(amountToPay)

    }

Structure

  • We define the Payment interface.
  • We have CreditCard and DebitCard implementations for the Payment specific for that type.
  • We have a Payment processor class that handles the payment and initiates it by redirecting it to appropriate implementations.

How open/closed principle is used here

  • Suppose you need to add a new payment method. In that case, you can create a new class that implements the Payment interface without modifying the existing code for the PaymentProcessor or any other payment method classes.
  • This adheres to the Open/Closed Principle, allowing the system to be easily extended with new functionality (new payment methods) without modifying existing code.