Why is an Enum considered more type-safe than constants?
-
09-10-2019 - |
سؤال
In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved type-safety):
public class OfficePrinter {
public enum PrinterState { Ready, OutOfToner, Offline };
public static final PrinterState STATE = PrinterState.Ready;
}
static final char MY_A_CONST = 'a';
المحلول
Imagine these two method signatures:
void rawF(char someFlag);
void enumF(MyFlags someFlag);
The latter is more restrictive as only the valid values of MyFlags
are allowed. In the former case, any character could be passed - even if only the values defined in "constants" where used.
Happy coding.
نصائح أخرى
You could pass MY_A_CONST to any method that takes a char. You could also pass any other char to a method that takes a char.
You could pass Ready, OutOfToner, Offline, and null to a method that takes a PrinterState.
You get safety by being able to limit the total set of values that can be passed to a method (or assigned to a variable).
Using enum
over constants helps with type safety because if a function takes an enum and you pass it anything but an enum, the compiler will complain. With constants, you're accepting a pretty large range of data, most of which are invalid.