Liskov substitution principle
Ben Finney
ben+python at benfinney.id.au
Fri Jul 15 21:47:19 EDT 2011
Chris Angelico <rosuav at gmail.com> writes:
> What if the base class implemented study(), and then LazyStudent
> subclasses Student but makes study() raise NotImpl? Would that break
> things? In a sense, it breaks the whole "this is a student so it
> should act like a student" rule.
That would break the Liskov substitution principle, yes. Anything that
asks for a Student instance should receive an object that can do at
least everything Student can do.
If you want to implement something that can't do some of the things
Student can do, the Liskov substitution principle says you are
implementing some object that does *not* inherit from Student.
This fits nicely with the principle (whose name I'm currently too lazy
to look up) that says you should only use inheritance for “IS-A”
relationships. If LazyStudent can't do everything Student can do, then
it's false to say LazyStudent IS-A Student, so using inheritance for
that would be to state something in code which isn't true.
> Suppose it raised UtterApathyError instead - does that break the LSP?
Probably, yes. Your point is taken though: it's not something that can
be drawn along a bright line.
--
\ “Those are my principles. If you don't like them I have |
`\ others.” —Groucho Marx |
_o__) |
Ben Finney
More information about the Python-list
mailing list