Enum의 압박

| | Comments (0) | TrackBacks (0)
#1. enum
public enum Coupon {
    saleCoupon("판매용"), sameCoupon("동일쿠폰");
   
    private String name;
    private Coupon(String name)
    {
       this.name = name;
    }
    private String getName()
    {
       return name;
    }
}


위와 같이 enum형을 선언했을때. String형의 입력을 받고 같은 이름을 가진 Coupon을 생성할때, 다음과 같은 코드를 작성하곤 했다.

String input = "saleCoupon";

Coupon c;
if(input.equals(Coupon.saleCoupon.toString()) {
    c = Coupon.saleCoupon;
} else if(input.equals(Coupon.sameCoupon.toString(){
    c = Coupon.sameCoupon;
}

오늘. 분명히 다른 방법이 있을 것이다.! 라고 믿고, Core Java를 뒤져보니 역시 다음과 같은 코딩방법이 있었다.

String input = "saleCoupon";

Coupon c = Enum.valueOf(Coupon.class, input);

조금 설렁~한 방법이긴 하지만, 다른 방법은 없는 것 같다. enum, 알아도 안쓰니 모르는 것만 못한것 같다.

#2. assert
enum형을 보다가 assert 예약어를 다시 훓어 보게 되었다. assert의 사용법은 다음과 같다.

assert condition;
또는
assert condition : expression;

예)
assert x >=0 : x;

if문을 쓰는것 보다 훨~ 씬 쉬울 것 같아 앞으로 자주 사용할까 했지만, 역시나 Test시에만 사용하는 이유가 있었다.
위의 condition이 옳지 않을 경우 AssertError 를 던진다. -_-;; (Exception이 아닌 Error이다.)
책에서도 내부 테스트 프로그램에서만 사용할 것을 권고하고 있다. 아쉽지만. 접자~



0 TrackBacks

Listed below are links to blogs that reference this entry: Enum의 압박.

TrackBack URL for this entry: http://dongchimi.unfix.net/mt/mt-tb.cgi/32

Leave a comment

Recent Comments

Sign In

About this Entry

This page contains a single entry by 동치미 published on March 15, 2008 12:44 AM.

느림의 미학 was the previous entry in this blog.

WP의 부활 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.