All Articles

Open and Closed Principle

This article was done using my notes from Vubon Roy & Deekey (2019).

Vubon Roy, (Nov 2, 2019), SOLID Principles with Python Examples, Medium.
Deekey, (Aug 2, 2019),S.O.L.I.D Principles explained in Python with examples.s, Medium.
Wikipedia, (2020), Robert C. Martin.

SOLID principles

SOLID principles are designed to guide Object Oriented Programing. The SOLID principles were defined in the early 2000s by Robert C. Martin.

SOLID stands for

1. Single Responsibility Principle
2. Open and Closed Principle
3. Lisvok Sub situation Principle
4. Interface Segregation Principle
5. Dependency Inversion Principle

Open and Closed Principle

Software entities (classes, function, module) open for extension, but not for modification (or closed for modification)

Violation of OCP

Let’s imagine you have a store, and you give a discount of 20% to your favorite customers using this class: When you decide to offer double the 20% discount to VIP customers.

class Discount:
  def __init__(self, customer, price):
      self.customer = customer
      self.price = price

  def give_discount(self):
      if self.customer == 'fav':
          return self.price * 0.2

      if self.customer == 'vip':
          return self.price * 0.4

How does it violate the OCP?

This example fails to pass the Open and Close Principle(OCP). It is hardly maintainable to add new cases each time we wish to create a special discount.

Solution

To make it follow the OCP principle, we will add a new class that will extend the Discount. In this new class, we would implement its new behavior.

class Discount:
    def __init__(self, customer, price):
      self.customer = customer
      self.price = price

    def get_discount(self):
      return self.price * 0.2

class VIPDiscount(Discount):
    def get_discount(self):
      return super().get_discount() * 2

class SuperVIPDiscount(VIPDiscount):
   """Demo super vip customer discount class"""
   def get_discount(self):
       """A discount method"""
       return super().get_discount() * 2