KB keyboard_arrow_right Java tips keyboard_arrow_right
1 - Use enums instead of constant classes or interfaces
1
Use enums instead of constant classes or interfaces
calendar_today
July 21
access_time
0min. read
remove_red_eye
307
thumb_up
3
comment
0
thumb_up
3
Many developers create final classes for storing constants or use interfaces. Enums are the best option to store constants.

To illustrate the point here are examples of those two most common patterns for storing constants:

Using a final class with static final fields:

public final class MyConstantKeeper {
    public static final int CONSTANT_ONE = 1;
    public static final int CONSTANT_TWO = 2;
    public static final int CONSTANT_THREE = 3;
}


A slightly better way to do that is to use an interface instead of a class, because interfaces already are abstract and kind of singleton, so their fields are final static 'by default':

Using interfaces:

public interface MyConstantHolder {
    int CONSTANT_ONE = 1;
    int CONSTANT_TWO = 2;
    int CONSTANT_THREE = 3;
}


Comments (0)