- Single Responsibility Principle
- Open/Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency of Inversion Principle
- Conclusion
Liskov Substitution Principle
The Liskov Substitution Principle (LS) [NES1] deals with interfaces. The premise is that any type derived from a base class should be able to be used in place of the base class.
I find this principle the most confusing because the whole idea of polymorphism and inheritance is to derive from base classes, but override the methods of the base class with a different implementation. But if you are just deriving classes without using interfaces, this problem can occur.
Take a look at the following code:
public class Rectangle { protected int m_width; protected int m_height; void setWidth(int width){ m_width= width; } void setHeight(int height){ m_eight = height; } public int getArea(){ return m_width * m_height; } } public class Square extends Rectangle { void setWidth(int width){ m_width = width; m_height = height; } void setHeight(int height){ m_width = width; m_height = height; } } class TestLsp { public static void main (String args[]) { Rectangle r = new Square(); r.setWidth(5); r.setHeight(10); System.out.println(r.getArea()); } }
Suppose that a developer creates a new instance of the Rectangle class, but instead uses the Square class. When the setWidth and setHeight functions are invoked, the area returned is 100, not 50, as it should be for a rectangle.
According to this principle, you should keep the behavior the same among derived classes with regard to the base class. If you want to provide different implementations between class methods, use interfaces or abstract classes so that each class method definition can be overridden with the desired implementation.
I have not often seen developers using a derived type in code; they usually assign it to return the base object.