java: is using a final static int = 1 better than just a normal 1?

后端 未结 7 1899
轻奢々
轻奢々 2020-12-11 06:47

I just saw a class (an big API module), where there is alot of stuff like

readParamString(Object params, int index)

and they have in that c

7条回答
  •  一向
    一向 (楼主)
    2020-12-11 07:14

    One advantage of declaring a static final constant is to prevent multiple references to the same literal value througout the code, which could potentially lead to unwanted variation; e.g. if a programmer inadvertently changes one literal without changing the others.

    In your example, I'd question the value of declaring a constant PARAM1 with the value 1, especially if this is private to the containing class and only referenced once. If however, there was some semantic meaning to the literal value then it might be more useful; e.g.

    public static final int LOAD_ACTION = 1;
    public static final int SAVE_ACTION = 2;
    public static final int DELETE_ACTION = 4;
    public static final int MOVE_ACTION = 8;
    

    However, typically an enum would be used instead of this approach.

提交回复
热议问题