티스토리 뷰
Tiny example - how immutable/readonly class helps OOP
Kaboomba 2022. 3. 13. 09:14I have read about Liskov Substitute Principle(LSP, https://en.wikipedia.org/wiki/Liskov_substitution_principle) few times and tried to understand correctly but it's clear sometimes but ambiguous other times. I confess it's not still 100 clear. I might need to revisit when I have a problem.
We can easily find long discussions about LSP(https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle) and it helps somehow but some of them makes me more confusing. While doing my reading I realised that one of core issue the example Rectange and Square example comes easily when we use mutable classes.
First, let's have a look at typcial example of Rectange and Square.
public class Rectangle {
private int width;
private int height;
public int getWidth() {
return this.width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return this.height;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width * height;
}
}
public class Square extends Rectangle {
}
We face critical issue when we set width or height in Squre class. If we dont' set wdith and height at the same time, width and height will not be the same and it won't be a square anymore. People try to fix the issue in many different apporach and this make the simple example very complicating. To me, main cause of the prolem come from setters, setWidth and setHeight. If we remove setters and use copy then, it can remove this side effect.
public class Rectangle {
private final int width;
private final int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public int getArea() {
return width * height;
}
}
public class Square extends Rectangle {
public Square(int side) {
super(side, side);
}
}
And we can copy fields when we need to change width or height.
Rectangle rectangle = new Square(10);
Rectangle newRectangle = new Rectangle(rectangle.width, 20);
There is no other way to modify its fields and won't break its original intention.
'Object Oriented Programming > Coding Practice 101' 카테고리의 다른 글
Take favour read-time convenience over write-time convenience (0) | 2022.02.07 |
---|