6

Java プロジェクトの多くで、データベースを広く使用しています。通常、property.xmlすべての文字列と設定を保持するファイルを用意しています。

そしてCNST、xml ファイル内の静的定数に対応するすべての静的定数を保持するクラスを作成します。

これらの定数は、プログラムの開始時に xml ファイルによって一度初期化され、プログラムの後半でグローバルとして使用されます。

しかし、最近多くの記事を読んだ後、グローバルをまったく使用することはあまり良い習慣ではないようです。ですから、この状況の良い習慣を誰かが示すことができますか? ありがとう。

4

4 に答える 4

3

グローバル変数を使用するということは、データを操作できる多くのクラスにそれらが可視であることを意味します。

そのため、データが広く表示されるように注意する必要があります。

また、マルチスレッドを使用している場合は、誰でもそのデータを変更できるため、問題が発生するため、データが破損する可能性が高くなります。

練習問題として、私は次の点に従います。

  1. 変数の可視性を最小限に保ち、可能であれば非公開にします。
  2. 可能な限り不変にします。
于 2013-08-11T06:26:07.377 に答える
0

You can freely use public static constants or variables. If you use non-static variables then good practice is to use Getters and Setters. If your class conatains only static constants then you can also use private constructor to restrict creating instances of this class.

public class Global {

    public static final int A;
    public static final int B;

    private Global() {} // use only when you have only static fields and methods

    static {
        A = 1;
        B = 2;
    }
}
于 2013-08-11T06:13:57.447 に答える
0

You can create a public static variable instead of Global variable that would be a better idea.

Check out this link.

One other approach is to create a class that follows the singleton pattern, so there can only be one instance of the class and keep the variable in the singleton class and access it with get and set methods.

Edit1:-

Go for the old style in case of declaring the constants. Something like this:-

(public/private) static final TYPE NAME = VALUE;

I would not recommend creating a class in that case.

于 2013-08-11T06:14:05.440 に答える