[JAVA] Use enum instead of int constant

int enum pattern

Poor expressiveness. Passing apple to the method expecting orange Even if you compare Apple and Orange with the == operator, the compiler doesn't get angry.

public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPIN = 1;
public static final int APPLE_GRANNY_SMITH = 2;

public static final int ORANGE_NAVEL = 0;
public static final int ORANGE_TEMPLE = 1;
public static final int ORANGE_BLOOD = 2;

When using enum

public enum Apple {FUJI, PIPIN, GRANNY_SMITH}
public enum Orange {NAVEL, TEMPLE, BLOOD}

Enum type to switch by value

In the code below, it is technically reachable to the end of the method, There is a problem such as forgetting to add a case corresponding to the switch

public enum Operation {
		PLUS, MINUS, TIMES, DIVID;

		//Perform arithmetic operations represented by constants
		public double apply(double x, double y) {
			switch(this) {
			case PLUS:
				return x + y;
			case MINUS :
				return x - y;
			case TIMES:
				return x * y;
			case DIVID:
				return x / y;
			}
			throw new AssertionError("Unknown op" + this);
		}
	}

The problem can be improved by defining an abstract method and overriding the abstract method for each constant.

public enum Operation {
		PLUS {
			public double apply(double x, double y) {
				return x + y;
			}
		},
		MINUS {
			public double apply(double x, double y) {
				return x - y;
			}
		},
		TIMES {
			public double apply(double x, double y) {
				return x * y;
			}
		},
		DIVIDE {
			public double apply(double x, double y) {
				return x + y;
			}
		};
		public abstract double apply(double x, double y);
	}

Apply more concisely by using lambda


public enum Operation {
    PLUS((x, y) -> x + y),
    MINNUS((x, y) -> x - y),
    TIMES ((x, y) -> x * y),
    DIVIDE ((x, y) -> x / y);

    private final DoubleBinaryOperator op;

    Operation (DoubleBinaryOperator op) {
        this.op = op;
    }

    public double apply(double x, double y) {
        return op.applyAsDouble(x, y);
    }
}

Recommended Posts

Use enum instead of int constant
Item 36: Use EnumSet instead of bit fields
Item 37: Use EnumMap instead of ordinal indexing
[Java] Why use StringUtils.isEmpty () instead of String.isEmpty ()
[Java] use Optional instead of if (hoge! = null) {...}
How to use enum (introduction of Japanese notation)
Why use setters/getters instead of public/private in Java
Use of Date class
[Swift] Why FlowLayout should use Delegate instead of instance
[Rails] How to use enum
[Rails] How to use enum
Use @ValueSource of ParametrisedTest of JUnit5