Search code examples
oopinheritancesolid-principlesliskov-substitution-principle

Violation of Liskov Substitution Principle in SharedFolder


The current design is

  1. SharedFolder is a subclass of Folder.
  2. SharedFile is a subclass of File with a remote resource URL.
  3. Folder accepts File in an add method.
  4. SharedFolder accepts only SharedFile but not non-shared File
  5. File can be moved to another Folder with add.
  6. The UI for browsing files in SharedFolder and Folder is mostly the same.

The add in SharedFile violate LSP. How to re-organize the object structure while allowing some UI code reuse?


Solution

  • You can genericize Folder as Folder<T extends File>, with add(T), and have SharedFolder extends Folder<SharedFile>.

    This way, SharedFolder is only expected to substitute another Folder<SharedFile>, but not any other type of Folder<File>

    (If your language allows it. This would be possible in Java)