My previous question was just with class diagram and because of some comments I thought I try to find an example with a little piece of code for the diagram to see if principles correct understood?
class Rectangle {
private int width, height;
public void setHeight(int h) { height = h; }
public void setWidth(int w) { width = w; }
public int area() { return height * width; }
}
class Square extends Rectangle {
public void setHeight(int h) { height = width = h; }
public void setWidth(int w) { width = height = w; }
}
// A test function for rectangles
public void areaTest(Rectange rect) {
rect.setHeight = 20;
rect.setWidth = 10;
int area = rect.area();
assert area == 200;
}
I think first problem is that Liskov Substitution Principle is hurt because square extends rectangle so there is no issue saying a square is a rectangle but you cannot say a rectangle is a square which the code does, so this principle is hurt I think for this reason.
Another hurt principle I believe is Single-Responsibility Principle because in class rectangle, in order to modify the properties of a rectangle for example its area(), you would need to change the entire implementation to achieve this, for the similar reason I believe the Open/Closed Principle is hurt as well because if you want add an extension let's say a draw function to draw the objects (rectangle/square), you cannot do this correctly.
I think other principles are not hurt by this design.