Z
Z
zlodiak2019-03-19 15:24:44
Python
zlodiak, 2019-03-19 15:24:44

Is it possible to improve the LSP example?

Tried to write some code illustrating the Liskov Substitution Principle (LSP). Please tell me, is it clear enough, is it possible to improve the example?
First, I give an example of incorrect code. Let's say there is a Clock class that has a method for displaying the time in unix format. As you can see, the programmer in the second instance has overridden the contents of this method. the user of the class does not expect the new behavior. This is an example of an LSP violation.

#!/usr/bin/env python3

from abc import ABCMeta, abstractmethod
import time
import datetime

class Clock(metaclass=ABCMeta):
  @abstractmethod
  def displayUnix(self):
    pass

class Clock1(Clock):
  def displayUnix(self):
    print('i am display UNIX: ', time.time())

class Clock2(Clock):
  def displayUnix(self):
    print('but i am display ISO: ', datetime.datetime.now().isoformat())    

clock1 = Clock1()
clock1.displayUnix()

clock2 = Clock2()
clock2.displayUnix()

Below is the code that fixes this possible situation. It is fully compliant with LSP:
#!/usr/bin/env python3

from abc import ABCMeta, abstractmethod
import time
import datetime

class Clock(metaclass=ABCMeta):
  @abstractmethod
  def displayUnix(self):
    pass

class Clock_(metaclass=ABCMeta):
  @abstractmethod
  def displayIso(self):
    pass

class Clock1(Clock, Clock_):
  def displayUnix(self):
    print('i am display UNIX: ', time.time())

  def displayIso(self):
    print('i am display ISO: ', datetime.datetime.now().isoformat())     

class Clock2(Clock, Clock_):
  def displayUnix(self):
    print('i am display UNIX: ', time.time())

  def displayIso(self):
    print('i am display ISO: ', datetime.datetime.now().isoformat())      

clock1 = Clock1()
clock1.displayUnix()
clock1.displayIso()

clock2 = Clock2()
clock2.displayUnix()
clock2.displayIso()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2019-03-19
@vt4a2h

There is a problem here: in the second example, both descendant classes are exactly the same. Those. the example shows nothing.
A good example of misuse would be when, for example, one successor throws an exception and the other does not. Well, right when it's not. Well, or show the amplification of the precondition. You can also show the problem with throwing different types of exceptions.

M
MechanicZelenyy, 2019-05-01
@MechanicZelenyy

The example is not very good, since in the second class the method simply does not work correctly --- errors in the algorithm, these are not design errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question