(Efficient Java) Point 23. 태그된 클래스 대신 클래스 계층 구조를 사용하십시오.

Point 23. 태그 클래스 대신 클래스 계층 구조를 사용하세요.

  • 태그가 지정된 클래스 – 클래스 계층 구조보다 훨씬 나쁩니다!
public class Figure {
    enum Shape { RECTANGLE, CIRCLE };

    // 태그 필드 - 현재 모양을 나타낸다.
    final Shape shape;

    // 다음 필드들은 모양이 사각형(RECTANGLE)일 때만 쓰인다.
    double length;
    double width;

    // 다음 필드는 모양이 원(CIRCLE)일 때만 쓰인다.
    double radius;

    // 원용 생성자
    Figure(double radius) {
        shape = Shape.CIRCLE;
        this.radius = radius;
    }

    // 사각형용 생성자
    Figure(double length, double width) {
        shape = Shape.RECTANGLE;
        this.length = length;
        this.width = width;
    }

    double area() {
        switch(shape) {
            case RECTANGLE:
                return length * width;
            case CIRCLE:
                return Math.PI * (radius * radius);
            default:
                throw new AssertionError(shape);
        }
    }
}

1⃣ 태그가 지정된 클래스는 장황하고 오류가 발생하기 쉬우며 비효율적입니다.

2⃣로 표시된 클래스는 클래스 계층 구조의 모형일 뿐입니다.

참고 자료

Joshua Bloch, 『Effective Java 3/E』, 잘 번역됨, Programming Insight (2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=