프로그래밍을 하다보면 약속이 필요한 경우가 종종 생긴다. 이 때 상수(Constant)를 활용하는 방법에 대해서 살펴본다.
형태
public static final double PI = 3.141592;
상수는 일반적으로 다음의 키워드를 붙여 표현한다.
public : 공개하여 접근에 제약이 걸리지 않도록 설정
static : 메모리에 프로그램 시작과 동시에 등록하여 편하게 접근
final : 불변 처리하여 안정성 확보
상수는 클래스 안에 위치해야 하며 이름은 대문자로 작성하는 것이 일반적이다. 주로 애플리케이션 내에서 영원히 변하지 않는 값을 표현할 때 사용한다.
데모 1 : 상수가 필요한 상황
public class ConstantExample01{
public static void main(String[] args){
//키보드 방향키를 다음과 같이 약속
//2(down), 4(left), 6(right), 8(up)
int direction = 2;
switch(direction){
case 2: System.out.println("down"); break;
case 4: System.out.println("left"); break;
case 6: System.out.println("right"); break;
case 8: System.out.println("up"); break;
}
}
}
코드상 문제될 내용은 없지만 상단에 작성한 주석이 없을 경우 코드를 파악하는 데 시간이 오래 걸린다. 이를 가독성이 나쁘다고 한다.
데모 2 : 상수 사용
public class ConstantExample02{
//상수는 클래스 안에 작성한다
public static final int UP = 8;
public static final int LEFT = 4;
public static final int RIGHT = 6;
public static final int DOWN = 2;
public static void main(String[] args){
int direction = DOWN;
switch(direction){
case DOWN: System.out.println("down"); break;
case LEFT: System.out.println("left"); break;
case RIGHT: System.out.println("right"); break;
case UP: System.out.println("up"); break;
}
}
}
주석 없이도 코드를 이해하는 것이 훨씬 쉬워졌다는 것을 알 수 있다. 이를 가독성이 좋아졌다고 한다. 같은 클래스에 상수를 배치하여 클래스명 없이 접근하였으나, 일반적으로 상수는 의미있는 클래스를 만들고 해당하는 클래스에 배치하는 것이 일반적이다.
데모 3 : 별도의 클래스에 상수 배치 및 사용
class Direction {
//상수는 클래스 안에 작성한다
public static final int UP = 8;
public static final int LEFT = 4;
public static final int RIGHT = 6;
public static final int DOWN = 2;
}
public class ConstantExample03{
public static void main(String[] args){
int direction = Direction.DOWN;
switch(direction){
case Direction.DOWN: System.out.println("down"); break;
case Direction.LEFT: System.out.println("left"); break;
case Direction.RIGHT: System.out.println("right"); break;
case Direction.UP: System.out.println("up"); break;
}
}
}
정상적으로 잘 실행되며, Direction이라는 클래스에 상수를 배치하였기 때문에 해당 상수에 대한 의미 전달도 명확해진 것을 알 수 있다.
Direction.UP
Direction.LEFT
Direction.RIGHT
Direction.DOWN
결론
상수를 이용하면 프로그래밍에서 필요한 약속들을 구체적인 값으로 명시할 수 있다. 자바에서는 상수가 더 발전되어 Enum이란 형태로 존재하며 이는 해당 문서에서 다룬다.