mardi 17 janvier 2023

Proper way to satisfy liskov substitution principle?

How should I properly satisfy the Liskov Substitution Principle in this sample?

class User(ABC):  # App core logic
    def add_photo(self, photo: bytes, ) -> None:
        ...


class FacebookUser(User):  # API interation logic
    def add_photo(self, photo: custom_type, ) -> None:
        ... # Set of Facebook specific actions.
        super().add_photo(photo=photo.bytes, )

I know 4 solutions:

  1. Name mangling. Flaws:
    Forcing me to rename all the existing code with Parent.add_photo and probably all the rest methods.
  2. Composition. Flaws:
    2.1. Can't reflect the logical relation between the classes.
    2.2 Forcing me to implement (proxy) methods for every Parent method.
  3. if checking for the self object type inside the method. Flaws:
    3.1. Additional complexity and clumsy branches.
  4. Implement convert_photo method from custom_type to bytes type inside the FacebookUser child class. Flaws:
    4.1 I still need to place a new convert_photo method inside some kinda "event" method (set of methods) and the best name for it is add_photo.

Aucun commentaire:

Enregistrer un commentaire