본문 바로가기

JAVA

코드성 데이터를 Java Enum으로 관리하는 방법에 대한 고찰

고정된 코드성 데이터를 가져오는 방법으로는 여러가지 방법이 존재합니다.

1) DB 테이블로 관리하며 SELECT 쿼리를 통해 가져오는 방법

2) 애플리케이션단에 정의하는 방법

 

두번째 방법으로 개발 시 관리를 효과적으로 할수 있을까?라는 고민에서 시작되었습니다.

 

예시는 다음과 같습니다. 국제팩스를 발송하는 애플리케이션을 개발하기 위해서는 필요한 데이터가 존재하며 데이터는 다음과 같습니다.

 

국가코드, 국가명, 포인트

 

Enum 클래스를 작성하여 국가코드를 기준으로 오름차순 정렬합니다.

 

 

//국가코드로 정렬
public enum InterPriceEnum {

	USA(1, "미국", 93),
	RUSSIA(7, "러시아", 591),
	GERMANY(49, "독일", 307),
	AUSTRALIA(61, "호주", 352),
	INDONESIA(62, "인도네시아", 355),
	SINGAPORE(65, "싱가폴", 320),
	JAPAN(81, "일본", 227),
	CHINA(86, "중국", 332),
	HONGKONG(852, "홍콩", 320),
	TAIWAN(886, "대만", 310);
	
	private int code;
	private String nation;
	private int point;
	
	InterPriceEnum(int code, String nation, int point) {
		this.code = code;
		this.nation = nation;
		this.point = point;
	}

	public int getCode() {
		return code;
	}

	public String getNation() {
		return nation;
	}

	public int getPoint() {
		return point;
	}
	
	
}

 

Enum을 통해 정의한다면 Enum 클래스에 정의된 데이터들을 가져올 수 있으며 BinarySearch를 통해 특정 값을 빠르게 검색할 수 있습니다. (시간복잡도 O(n))

 

 

	//코드성 데이터 배열 생성
	public static InterPriceEnum[] createInterPrice() {
		return InterPriceEnum.class.getEnumConstants();
	}

	//특정 코드가 존재하는지 확인
	public static boolean existInterPrice(InterPriceEnum[] interprices, int code) {
		
		InterPriceEnum interpriceEnum = findInterPrice(interprices, code);
		return interpriceEnum.getCode() == code;
	}

	//특정 코드 데이터 찾기
	public static InterPriceEnum findInterPrice(InterPriceEnum[] interprices, int code) {
		int idx = binarySearch(interprices, code);
		return interprices[idx];
	}
	
	//이분 탐색
	public static int binarySearch(InterPriceEnum[] interprices, int code) {
		
		int left = 0 ;
		int right = interprices.length-1;
		int mid = 0;
		
		while(left < right) {
			mid = (left + right)/2;
			
			if(interprices[mid].getCode() >= code) {
				right = mid;
			}
			else {
				left = mid+1;
			}
		}
		
		return right;
	}

 

BinarySearch를 통해 탐색 시 시간복잡도는 O(n)에서 O(logn)으로 성능이 향상됨을 알 수 있습니다.

InterPriceEnum 클래스를 FlyWeight 패턴을 적용하여 Local Cache 저장소에 저장한다면 더 뛰어난 성능을 보장할 수 있습니다.