아이템34 int 상수 대신 열거 타입을 사용하라
Effective Java 3e 아이템 34를 요약한 내용 입니다.
public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPPIN = 1;
public static final int APPLE_GRANNY_SMITH = 2;
public static final int ORANGE_NAVEL = 0;
public static final int ORANGE_TEMPLE = 1;
public static final int ORANGE_BLOOD = 2;정수 열거 패턴 기법에는 단점이 많다.
열거 타입을 쓰면 어떤 부분이 장점이 있을까
public class WeightTable { public static void main(String[] args) { double eartchWeight = Double.parseDouble(args[0]); double mass = earchWeight / Planet.EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("%s에서의 무게는 %f이다.\\n",p,p.surfaceWeight(mass)); } }public enum Operation { PLUS("+") { public double apply(double x, double y) { return x + y; } } MINUS("-") { public double apply(double x, double y) { return x - y; } ... }public static void main(String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); for (Operation op : Operation.values()) System.out.printf("%f %s %f = %f\\n", x, op, y, op.apply(x,y)); }public static Operation inverse(Operation op) { switch(op) { case PLUS: return Operation.MINUS; case MINUS: return Operation.PLUS; case TIMES: return Operation.DIVIDE; case DIVIDE: return Operation.TIMES; default: throw new AssertionError("알 수 없는 연산 : "+ op); } }
열거 타입에서 상수를 하나 제거하면 어떻게 되지?

정리
Last updated