Enum

이영재·2022년 5월 29일

Enum에 대해 막상 사용하려고 하면 헷갈리는 경우가 많았다.
직접 사용해봤던 예시를 통해 기억해보자.

nextstep TDD, Clean Code with Java(14기) 강의를 들으면서 사칙연산에 대한 Enum 클래스를 구현해보았다.

람다식까지 활용하여 좀 더 간결하게 구현해볼 수 있었다.

package stringcalculator;

import java.util.Arrays;
import java.util.function.BiFunction;

public enum Operator {
    ADDITION("+", (firstOperand, secondOperand) -> firstOperand + secondOperand),
    SUBTRACTION("-", (firstOperand, secondOperand) -> firstOperand - secondOperand),
    MULTIPLICATION("*", (firstOperand, secondOperand) -> firstOperand * secondOperand),
    DIVISION("/", (firstOperand, secondOperand) -> firstOperand / secondOperand);

    private String operatorCode;
    private BiFunction<Integer, Integer, Integer> calculation;

    Operator(String operatorCode, BiFunction<Integer, Integer, Integer> calculation) {
        this.operatorCode = operatorCode;
        this.calculation = calculation;
    }

    public static Operator from(String operatorCode) {
        return Arrays.stream(values())
                .filter(operator -> operator.operatorCode.equals(operatorCode))
                .findFirst().orElseThrow(() -> new IllegalArgumentException("연산자는 +, -, *, / 기호만 입력 가능합니다."));
    }

    public static String calculate(String operatorCode, String firstOperand, String secondOperand) {
        return toString(from(operatorCode).calculation.apply(toInt(firstOperand), toInt(secondOperand)));
    }

    private static int toInt(String operand) {
        return Integer.parseInt(operand);
    }

    private static String toString(int operand) {
        return String.valueOf(operand);
    }
}

Enum을 통해 얻는 장점

  • 실행되는 코드를 이해햐기 위해 추가로 무언가를 찾아보는 행위를 최소화 할 수 있다.





참고 링크
https://techblog.woowahan.com/2527/

profile
왜why를 생각하는 두괄롬이 되자!

0개의 댓글