Why is Enum considered safer in type than constants?

In our example, we can choose the Enumerated Type option, which will limit 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';
+3
source share
3 answers

Imagine these two method signatures:

void rawF(char someFlag);

void enumF(MyFlags someFlag);

The latter is more restrictive since only valid values ​​are allowed MyFlags. In the first case, any character can be transmitted - even if only the values ​​defined in the "constants" are used.

Happy coding.

+17
source

MY_A_CONST , char. char , char.

Ready, OutOfToner, Offline null , PrinterState.

, , ( ).

+1

enum , , -, , . , .

+1

Source: https://habr.com/ru/post/1770406/


All Articles