Skip to content

Instantly share code, notes, and snippets.

@eric-hu
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric-hu/ced35c0e76f7f25ddee2 to your computer and use it in GitHub Desktop.
Save eric-hu/ced35c0e76f7f25ddee2 to your computer and use it in GitHub Desktop.
Liskov Substitution Principle

"If S is a subtype of T, then objects of type S should be able to replace objects of type T without altering desireable properties of the program"

=====

Goals of SOLID:

  • Address problems of rotting design
    • Rigidity
      • small changes take a long time
      • affects management
        • code freezes
        • feature freezes

=====

  • Fragility
    • changes create bugs
    • bug fixes create more bugs

=====

  • Immobility
    • little to no code re-use
      • re-writing similar tools throughout the system
      • dependencies of old tools make them too difficult to extract

=====

  • Viscocity
    • 2 types:
      • (software) design
        • sticking to the design costs more than adding hacks
      • environment
        • hour long compile times, build times, deploy times

=====

  • SOLID(er)
    • "Dependencies (and dependency changes) are the cause of design rot"
    • set up design firewalls
      • don't allow dependency changes to propagate across the system

=====

Liskov Substitution Principle

  • "If S is a subtype of T, then objects of type S should be able to replace objects of type T without altering desireable properties of the program"

=====

  • Stated another way
    • "Preconditions are no stronger than the base class' method"

    • "Postconditions are no weaker than a base class' method"

    • "Expect no more, provide no less"

=====

  • Seems a bit obvious?
    • Violations of LSP become OCP violations

=====

  • Example
    • Circle-ellipse problem
      • "Circle is an ellipse"
      • class Circle < Ellipse
        • violates "preconditions are no stronger"
        • code that tries to set major/minor axes independently will have unexpected results

=====

  • Person-prisoner inheritance [1]
    • person method has move_north(meters)
    • violates "preconditions are no stronger"
    • a prisoner doesn't have the same freedom to move

=====

  • Honorable mention
    • Does Liskov substitution apply to interfaces? [2]
    • Prefer composition to inheritance [3]

References

[1] http://en.wikipedia.org/wiki/Circle-ellipse_problem#Challenge_the_premise_of_the_problem

[2] http://stackoverflow.com/questions/12252363/does-liskov-substitution-principle-also-apply-to-classes-implementing-interfaces

[3] http://en.wikipedia.org/wiki/Composition_over_inheritance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment