Best Practice: Java static non final variables

前端 未结 7 856
北荒
北荒 2020-12-08 15:03

In Java, when should static non final variables be used?

For example

private static int MY_VAR = 0;

Obviously we are not talking ab

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 15:35

    In my experience static non-final variables should only be used for singleton instances. Everything else can be either more cleanly contained by a singleton (such as a cache), or made final (such as a logger reference). However I don't believe in hard and fast rules, so I would take my advice with a grain of salt. That said I would suggest carefully examining any case where you consider declaring a non-final static variable aside from a singleton instance and see if it can be refactored or implemented differently -- i.e. moved into a singleton container or use a final reference to a mutable object.

提交回复
热议问题