Z
Z
zlodiak2019-03-19 17:50:37
Python
zlodiak, 2019-03-19 17:50:37

Is it possible to improve the ISP example?

Wrote code illustrating the interface separation principle (ISP). Tell me, is everything clear and clear? Is it possible to improve it?
Here is a wrong example, here the worker has the opportunity to increase his salary:

from abc import ABCMeta, abstractmethod

class Person(metaclass=ABCMeta):
  def __init__(self, pay):
    self.pay = pay

  @abstractmethod
  def getPay(self):
    pass

  @abstractmethod
  def setPay(self):
    pass    

class Boss(Person):
  def getPay(self):
    print('i am boss. my pay is: ', self.pay)

  def setPay(self, pay):
    self.pay = pay

class Worker(Person):
  def getPay(self):
    print('i am worker. my pay is: ', self.pay)

  def setPay(self, pay):
    self.pay = pay    

boss = Boss(100)
boss.getPay()
boss.setPay(120)
boss.getPay()

worker = Worker(10)
worker.getPay()
worker.setPay(20)
worker.getPay()

And here is a correct example. Here, the worker does not have the opportunity to increase his salary, because his class implements only the interface corresponding to the status, and not all of them:
from abc import ABCMeta, abstractmethod

class Person(metaclass=ABCMeta):
  def __init__(self, pay):
    self.pay = pay

  @abstractmethod
  def getPay(self):
    pass


class Person_(metaclass=ABCMeta):
  @abstractmethod
  def setPay(self):
    pass    


class Boss(Person, Person_):
  def getPay(self):
    print('i am boss. my pay is: ', self.pay)

  def setPay(self, pay):
    self.pay = pay

class Worker(Person):
  def getPay(self):
    print('i am worker. my pay is: ', self.pay) 

boss = Boss(100)
boss.getPay()
boss.setPay(120)
boss.getPay()

worker = Worker(10)
worker.getPay()
worker.setPay(20)   # error
worker.getPay()

I tried to shorten and simplify the example code as much as possible, but so that the understandability of the material does not suffer. Did it work?
Perhaps I myself do not fully understand the principle of ISP. And it will be too early to explain to someone else ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2019-03-19
@longclaps

Perhaps python is the most inappropriate language for all the encapsulation bullshit. Nothing prevents you from doing this or that or even that

worker = Worker(10)
worker.getPay()
worker.__class__.setPay = Boss.setPay #  мутим
worker.setPay(100500)                 #  мутим
del worker.__class__.setPay           #  мутим
worker.getPay()
worker.setPay(20)                     #  я не при делах!
worker.getPay()

Attempts to get around this - like a barrier in an open field)

M
MechanicZelenyy, 2019-05-01
@MechanicZelenyy

Replace Person_ with something more meaningful.
Use property.
Use something with static typing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question