WTC - 상수

김진성·2024년 11월 5일

WTC

목록 보기
4/6

값을 하드 코딩하지 않고 상수를 사용하면 코드의 유지보수성과 가독성을 크게 향상할 수 있다. 문자열, 숫자 값, 특정 설정 값 등을 하드 코딩하지 않고 static final 상수로 정의해 사용하면, 값의 의미가 더 명확해지고, 코드 중복을 줄이며 변경 시에도 한 곳에서 쉽게 관리할 수 있다.

예시 1: 문자열 상수 사용

하드 코딩된 문자열을 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);
    }
}

예시 2: 숫자 상수 사용

하드 코딩된 숫자 값을 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;
    }
}

예시 3: 특정 설정 값 상수 사용

애플리케이션 설정 값이나 경로 같은 값들을 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");
    }
}

예시 4: 열거형(enum)과 함께 상수 사용

일정 범위 내에서 특정 값만 사용할 수 있는 경우, enumstatic 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());
        }
    }
}
profile
minimalist

0개의 댓글