Java的不良做法是哪种全局变量? [英] What kind of global variable is bad practice in java?

查看:70
本文介绍了Java的不良做法是哪种全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的许多Java项目,我广泛使用数据库,通常要做的是拥有一个property.xml文件来保存我的所有字符串和设置.

For many of my java projects, I use database extensively, what I usually do is to have a property.xml file to hold all my strings and settings.

然后,我将拥有一个类CNST来保存与xml文件中的静态常量相对应的所有静态常量.

And then I would have a class CNST to hold all the static constants corresponding to those in the xml file.

这些常数在程序启动时由xml文件初始化一次,并在以后的程序中的任何地方用作全局变量.

Those constants are initialized by the xml file once when the program starts, and used as globals anywhere later on in the program.

但是,这几天看了很多文章之后,似乎根本不使用全局变量是一种好习惯.因此,请问有人可以指出这种情况的良好做法吗?谢谢.

However, after reading many articles these days, it seems that using globals at all is not such a good practice. So please can anyone may indicate a good practice fo this situation? Thanks.

推荐答案

通常,应尽可能避免使用全局变量=>但是,如果它们是常量,则这不是问题.对于这样的情况,当您(大概)在开始时初始化此全局设置包装器对象,但此后没有任何更改时,可以使用以下选项:

In general global variables should be avoided when it is possible => this however is not an issue if they are constants. For cases like this one when you (presumably) initialize this global-settings wrapper object at the beginning and nothing is changed afterwards, there are these options:

  • 具有在static块中初始化的常量(public static final)
  • 具有在static块中初始化并通过getter公开的变量private static final.
  • 创建一个单例并通过getter公开变量private final
  • Having constants (public static final) which are initialized in static block
  • Having the variables private static final initialized in static block and exposed via getters
  • Creating a singleton and having the variables private final exposed via getters

第二点和第三点比第一点有优势,在getter方法中,您封装了变量的值,并且可以更改/插入代码,该代码操纵要返回给调用方法的值,而不会影响依赖于该方法的(调用)代码

The 2nd and 3rd point has advantage over the 1st that in getter methods you have encapsulated the values of variables and can change/insert code which manipulates the value to be returned to calling method without effecting the (calling) code dependent on it.

这篇关于Java的不良做法是哪种全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆