Where do you keep Constants used throughout your application?

前端 未结 5 1144
小蘑菇
小蘑菇 2021-02-05 03:59

Is interface an acceptable place to store my

public static final Foo bar

Do you extrapolate them to be read from outside of the program? Do you

5条回答
  •  离开以前
    2021-02-05 04:25

    I've used Abdullah Jibaly's approach but using nested classes, which provides a nice way for grouping consts. I've seen this go 3 levels deep and if good names are chosen, it can still work quite well.

    One might choose to use final classes for this instead of interface classes to avoid violating Item #19 on Josh Bloch's list (Effective Java 2nd edition).

    public final class Const {
        private Const() {} // prevent instantiation
    
        /** Group1 constants pertain to blah blah blah... */
        public static final class Group1 {
            private Group1() {} // prevent instantiation
    
            public static final int MY_VAL_1 = 1;
            public static final int MY_VAL_2 = 42;
        }
    
        /** Group2 constants pertain to blah blah blah... */
        public static final class Group2 {
            private Group2() {} // prevent instantiation
    
            public static final String MY_ALPHA_VAL = "A";
            public static final String MY_ALPHA_VAL = "B";
        }
    
    }
    

提交回复
热议问题