All Articles

Interface Segregation 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

Interface Segregation Principle

This principle suggests that below two points. a. High-level modules should not depend on low-level modules. Both should depend on abstractions. b. Abstractions should not depend on details. Details should depend on abstractions.

Violation of ISP

class Shape:
   """A demo shape class"""
    def draw_circle(self):
       """Draw a circle"""
       raise NotImplemented   
    
    def draw_square(self):
       """ Draw a square"""
       raise NotImplemented

class Circle(Shape):
    """A demo circle class"""
    def draw_circle(self):
       """Draw a circle"""
       pass   
    
    def draw_square(self):
       """ Draw a square"""
       pass

How does it violate the ISP?

In the above example, we need to call an unnecessary method in the Circle class. Hence the example violated the Interface Segregation Principle.

Solution

class Shape:
   """A demo shape class"""
   def draw(self):
      """Draw a shape"""
      raise NotImplemented

class Circle(Shape):
   """A demo circle class"""
   def draw(self):
      """Draw a circle"""
      pass

class Square(Shape):
   """A demo square class"""
   def draw(self):
      """Draw a square"""
      pass