๋ฆฌ์Šค์ฝ”ํ”„ ์น˜ํ™˜ ์›์น™(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๋ฅผ ํ†ตํ•ด ์ž์‹ ํด๋ž˜์Šค๊ฐ€ ๋ถ€๋ชจ ํด๋ž˜์Šค์˜ ์—ญํ• ์„ ์ถฉ์‹คํžˆ ํ•˜๋ฉด์„œ ํ™•์žฅํ•ด๋‚˜๊ฐ€์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

Reference