What does the letter L in SOLID principles stand for?
sobes.tech AI
Answer from AI
L stands for the Liskov Substitution Principle.
This principle states that objects of a base class should be replaceable with objects of a derived class without affecting the correctness of the program. In other words, if S is a subtype of T, then objects of type T can be replaced with objects of type S.
Violation example:
public class Rectangle {
protected int width;
protected int height;
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width * height;
}
}
public class Square extends Rectangle {
@Override
public void setWidth(int width) {
this.width = width;
this.height = width; // Violation of LSP
}
@Override
public void setHeight(int height) {
this.width = height; // Violation of LSP
this.height = height;
}
}
In this example, Square violates LSP because the setHeight method in Square also changes width, which is not expected from Rectangle. Code written to work with Rectangle may not work correctly with Square.
Correct adherence example:
public interface Shape {
int getArea();
}
public class RectangleWithLSP implements Shape {
protected int width;
protected int height;
public RectangleWithLSP(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public int getArea() {
return width * height;
}
}
public class SquareWithLSP implements Shape {
protected int side;
public SquareWithLSP(int side) {
this.side = side;
}
@Override
public int getArea() {
return side * side;
}
}
Here, RectangleWithLSP and SquareWithLSP implement the same Shape interface, and their methods behave as expected, which complies with LSP.
Adhering to LSP helps create more flexible, extendable, and maintainable systems, preventing unexpected behavior when using subtypes.