If you specify unknown / default in java enumerations

For best practice, is it better to have the code as shown below using return "red" to simulate an unknown value? Or should I add an unknown("red") parameter and do a return Shape.unknown.color; ? Is there a standard Java convention for listings of 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"; } 
+4
source share
2 answers

Enumeration is an implicit kind of variable that should not have an uninitialized value.

In fact, your reasoning is true for each type of variable, and not just for enumerations, but in the specific case of enumerations, you declare a type that can have a finite number of possible values, so null should not be an option.

The best solution really has 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 each variable of type Shape to Shape.UNKNOWN to avoid performing a null check, which is a kind of null design pattern . This template makes even more sense when working with enumerations.

Note: since enumerations represent constants, conventions must give them uppercase names with underscores.

+7
source

Presumably, the form variable will be empty if it is unknown, so I would choose the static method that passed your instance to

 public static String getShapeColor(Shape shape) { if(shape != null) { return shape.color; } return "red"; } 
0
source

All Articles