๋ฆฌ์ค์ฝํ ์นํ ์์น(Liskov Substitution Principle)
์์ ํด๋์ค๋ ์ต์ํ ์์ ์ ๋ถ๋ชจ ํด๋์ค์์ ๊ฐ๋ฅํ ํ์๋ ์ํํ ์ ์์ด์ผ ํ๋ค.
Example
์๋๋ ๋์ด์ ๋๋น๋ฅผ ๊ฐ์ง๋ Rectangle
ํด๋์ค ์
๋๋ค.
class Rectangle {
private int width;
private int height;
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return this.height;
}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return this.width;
}
public int area() {
return this.width * this.height;
}
}
Rectangle
์ ์์๋ฐ๊ณ ์๋ Square
๋ผ๋ ํด๋์ค์
๋๋ค. setHight(int value)
์ setWidth(int value)
๋ฅผ Overrideํ๊ณ ์์ต๋๋ค.
class Square extends Rectangle {
@Override
public void setHeight(int value) {
this.width = value;
this.height = value;
}
@Override
public void setWidth(int value) {
this.width = value;
this.height = value;
}
}
ํ ์คํธ ์ฝ๋๋ฅผ ๋ณผ๊น์?
๋์ด 4, ๋๋น 5๋ก ์ค์ ํ์ฌ ๋์ด๋ฅผ ๊ตฌํ๊ณ ํ์ธํ๋ ํจ์์
๋๋ค. ๋ถ๋ชจ ํด๋์ค์ธ Rectangle
์ ๊ฒฐ๊ณผ ๊ฐ์ true๋ฅผ ํ์ธ ํ ์ ์์ง๋ง Square
๋ false๋ก ํ์ธ ํ ์ ์์ต๋๋ค.
class Test {
static boolean checkAreaSize(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
if(r.area() != 20 ){ // Error Size
return false;
}
return true;
}
public static void main(String[] args){
Test.checkAreaSize(new Rectangle()); // true
Test.checkAreaSize(new Square()); // false
}
}
์์ ์์๋ LSP
๋ฅผ ์๋ฐํ ํ๋์ ์์ ๋ก ๋ณผ ์ ์์ต๋๋ค. ์์ ํด๋์ค Square
๋ ๋ถ๋ชจ ํด๋์ค Rectangle
์ area()
๊ธฐ๋ฅ์ ์ ๋๋ก ํ์ง ๋ชปํ๊ณ ์์ต๋๋ค.
๊ทธ๋ฌ๋ฉด ๊ณผ์ฐ Square
๋ Rectangle
์ ์์์ด ๋ง์๊น๋ผ๋ ์์ฌ์ ํด๋ด์ผ ํฉ๋๋ค. ์์ ํด๋์ค๋ ์ต์ํ ์์ ์ ๋ถ๋ชจ ํด๋์ค์์ ๊ฐ๋ฅํ ํ์๋ ์ํํ ์ ์์ด์ผ ํ๊ธฐ ๋๋ฌธ์
๋๋ค.
ํด๊ฒฐ ๋ฐฉ๋ฒ
- ์์์ ๊ด๊ณ๋ฅผ ์ ๊ฑฐํ๋ ๋ฐฉ๋ฒ.
- ๊ธฐ๋ฅ์ ์ ๋๋ก ํ์ง ๋ชปํ๋
area()
๋ฅผ ์์ ํด๋์ค๋ก ์ด๋์ํค๋ ๋ฐฉ๋ฒ.
Result
- LSP๋ฅผ ํตํด ์์ ํด๋์ค๊ฐ ๋ถ๋ชจ ํด๋์ค์ ์ญํ ์ ์ถฉ์คํ ํ๋ฉด์ ํ์ฅํด๋๊ฐ์ผ ํ๋ค๋ ๊ฒ์ ์๊ฒ ๋์๋ค.