Interface segregation
Lesson 25 of 28 in Coddy's Clean Code - Write better code using Python course.
"Many client-specific interfaces are better than one general-purpose interface."
An interface is a description of behaviors that an object can do.
The interface segregation principle states that an interface should be as small a possible in terms of cohesion. In other words, it should only do ONE thing.
Let's see a bad example and we will fix it,
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def walk(self):
pass
@abstractmethod
def swim(self):
passThis is interface with multiple responsibilities!
And we will have problem when implementing this,
class Frog(Animal):
def walk(self):
print("Walking")
def swim(self):
print("Swimming")
class Giraffe(Animal):
def walk(self):
print("Walking")
def swim(self):
raise Exception("Girrafe cannot swim!")As you see this interface is not compatible with animals which cannot walk and swim!
Challenge
EasyLet's fix the above example by implementing Walkable and Swimable classes, you are given Frog and Giraffe classes which implements the new classes
Tasks:
- Create abstract class
Walkablewhich has only one abstract functionwalk(self) - Create abstract class
Swimablewhich has only one abstract functionswim(self)
Do not change the given code!
Notice that now each interface has only one responsibility and follows the principle
Try it yourself
from abc import ABC, abstractmethod
# Enter you code here
class Frog(Walkable, Swimable):
def walk(self):
print("Walking")
def swim(self):
print("Swimming")
class Giraffe(Walkable):
def walk(self):
print("Walking")
if __name__ == "__main__":
animal_type = input()
if animal_type == "frog":
animal = Frog()
animal.walk()
animal.swim()
elif animal_type == "giraffe":
animal = Giraffe()
animal.walk()
print("not Swimming")