값을 하드 코딩하지 않고 상수를 사용하면 코드의 유지보수성과 가독성을 크게 향상할 수 있다. 문자열, 숫자 값, 특정 설정 값 등을 하드 코딩하지 않고 static final 상수로 정의해 사용하면, 값의 의미가 더 명확해지고, 코드 중복을 줄이며 변경 시에도 한 곳에서 쉽게 관리할 수 있다.
하드 코딩된 문자열을 static final 상수로 대체하면 의미를 명확히 하고, 여러 곳에서 동일한 문자열을 사용할 때 코드의 일관성을 유지할 수 있다.
public class Print {
// 문자열 상수 정의
private static final String WELCOME_MESSAGE = "Welcome to the application!";
private static final String ERROR_MESSAGE = "An error occurred.";
public void printWelcomeMessage() {
System.out.println(WELCOME_MESSAGE);
}
public void printErrorMessage() {
System.out.println(ERROR_MESSAGE);
}
}
하드 코딩된 숫자 값을 static final 상수로 정의하여, 값의 의미를 더 명확히 하고, 코드 수정 시에도 한 곳에서 쉽게 관리할 수 있다.
public class MathConstants {
// 숫자 상수 정의
private static final int MAX_RETRIES = 3;
private static final double PI = 3.14159;
public boolean canRetry(int attempt) {
return attempt < MAX_RETRIES;
}
public double calculateCircleArea(double radius) {
return PI * radius * radius;
}
}
애플리케이션 설정 값이나 경로 같은 값들을 static final 상수로 정의하여, 하드 코딩된 값을 피하고 쉽게 관리할 수 있게 한다.
public class Config {
// 설정 상수 정의
private static final String API_URL = "https://api.example.com";
private static final int TIMEOUT_SECONDS = 30;
public void connect() {
System.out.println("Connecting to " + API_URL);
System.out.println("Timeout: " + TIMEOUT_SECONDS + " seconds");
}
}
일정 범위 내에서 특정 값만 사용할 수 있는 경우, enum과 static final 상수를 결합해 의미 있는 코드를 작성할 수 있다.
public class StatusCodes {
// 상수 정의
public static final int STATUS_OK = 200;
public static final int STATUS_NOT_FOUND = 404;
public static final int STATUS_ERROR = 500;
public enum Status {
OK(STATUS_OK),
NOT_FOUND(STATUS_NOT_FOUND),
ERROR(STATUS_ERROR);
private final int code;
Status(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
public void handleResponse(Status status) {
if (status == Status.OK) {
System.out.println("Request succeeded with status: " + status.getCode());
} else {
System.out.println("Request failed with status: " + status.getCode());
}
}
}