1) Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
2) If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
a) benefits of loose coupling outweight the risks of not complying to LSP
b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
thank you
LSP applies to the contract. The contract may be a class or an interface.
It’s not about an interface or a class. It’s about a violation of the contract. Let’s say that you have a
Break()method in aIVehicle(orVehicleBase). Anyone calling it would expect the vehicle to break. Imagine the surprise if one of the implementations didn’t break. That’s what LSP is all about.ehh?
ehh?
You might want to read my SOLID article to understand the principle better: http://blog.gauffin.org/2012/05/solid-principles-with-real-world-examples/
Update
Yes. That’s good. members (fields) should always be protected ( = declared as private). Only the class that defined them really know what their values should be.
That’s a violation of Open/closed principle. i.e. the class contract is changed by changing the behavior. Classes should be extended and not modified. Sure, it’s not possible all the time, but changes should not make the class behave differently (other than bugfixes).
There is a common reason to why extension through inheritance is hard. And that’s because the relationship isn’t a true
is-arelationship, but that the developer just want to take advantage of the base class functionality.That’s wrong. Better to use composition then.