λ¦¬μŠ€μ½”ν”„ μΉ˜ν™˜ 원칙(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