Java Eunm 사용기2

Enum 사용기 이어서 주어진 코드를 보고 리팩토링을 해본다.

  • discount() 메소드 내부 if 문 제고해보기
  • discountPercent 회원 등급에 따라 차별 할인이 있다. 10, 20, 30 각각 할당하고 있는데 Enum 에서 관리 형태로 바꾼다.

Grade.class

public enum Grade {
    BRONZE, SILVER, GOLD;    
}

DiscountService.class

public class DiscountService {
    public int discount(Grade grade, int price) {
        int discountPercent = 0;

        if (grade == Grade.BRONZE) {
            discountPercent = 10;
        } else if (grade == Grade.SILVER) {
            discountPercent = 20;
        } else if (grade == Grade.GOLD) {
            discountPercent = 30;
        } else {
            System.out.println("할인 없음");
        }

        return discountPercent * price / 100;
    }
}

리팩토링

Grade.class

public enum Grade {
    BRONZE(10), SILVER(20), GOLD(30);

    private final int discountPercent;
    
    Grade(int discountPercent) {
        this.discountPercent = discountPercent;
    }

    public int getDiscountPercent() {
        return discountPercent;
    }
}
  • Grade 생성 시 생성자자 통해서 인스턴스를 생성한다.
  • DiscountPercent 필드를 추가하고 생성자에서 필드 값을 저장한다.
  • 참고로 열거형은 상수외 생성이 불가능하다. 생성자는 private 고정으로 다른 접근제어를 선언할 수 없다.
  • BRONZE(10) 상수 선언 시 생성자에 맞게 인수를 전달하면 생성자는 알아서 호출한다.
  • 마지막 getter 메소드로 DiscountPercent 필드를 호출한다.

DiscountService.class

public class DiscountService {
    public int discount(Grade grade, int price) {

        return grade.getDiscountPercent() * price / 100;
    }
}
  • 불필요한 if문을 제거하고 getDiscountPercent() 호출하여 연산한다.

IDEA 도구 리팩토링 트릭

변수를 선언하고 할당 하는 코드를 한 줄로 한 것을 볼 수 있다.
IDE에서 자동으로 리팩토링 기능으로 인라인화 라는 기능을 제공하는데
변수명에 커서를 두고 Ctrl+Alt+N 누르면 리팩토링 기능이 수행되어 한줄로 생성한다.

IDEA 리팩토링 수행 전

IDEA 리팩토링 수행 후