Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you include unknown/default value in java enums

For best practices, is it better to have the code as it is below with the return "red" to simulate an unknown value? Or should I add an unknown("red") option and do return Shape.unknown.color; ? Is there a standard Java convention for enums about unknown values?

private enum Shape {
    triangle("yellow"),
    square("green"),
    circle("red");

    private final String color;
    Shape(String color) {
        this.color = color;
    }
};

public String getShapeColor() {
    if(shape != null) {
        return shape.color;
    }
    return "red";
}
like image 300
jb. Avatar asked Jan 08 '13 02:01

jb.


1 Answers

An enum is implicitly a kind of variable which is not supposed to have an uninitialized value.

Actually your reasoning is true for every kind of variable, not just enums, but in the specific case of enums you declare a type which can have a finite number of possible values so null shouldn't be an option.

Best solution is indeed to have an unknown value:

private enum Shape {
    TRIANGLE("yellow"),
    SQUARE("green"),
    CIRCLE("red"),

    UNKNOWN("unknown");

    private final String color;
    Shape(String color) {
        this.color = color;
    }
};

And initialize every variable of Shape type to Shape.UNKNOWN just to avoid doing any null check, which is a sort of null design pattern. This pattern makes even more sense when working with enums.

A note: since enums represent constants, conventions are to give them uppercase names with underscore.

like image 149
Jack Avatar answered Oct 04 '22 00:10

Jack