LoginSignup
8

More than 5 years have passed since last update.

変数の初期化にメソッドを用いる -final付与のために-

Last updated at Posted at 2015-08-06

特に変更されないはずの変数(*1)にはfinalを付けることで、その変数が存在するスコープ内の状態パターンが減り、デバッグ可能性や可読性が向上する。

(*1 特にImmutableクラスやプリミティブ型)
上記の理解のもとで、なるべく変数にはfinalを付与するように心がけています。

ここで、

sample1.java
//....
final int x = .....; // X は外部パラメータから取得
String t = "";
if(x == 0) t = "test";
if(x > 0) t = "sample";
if....;

System.out.println(t);

または、

sample2.java
//....
switch(x) {
    case 0:
        t = "test";
        break;
    case 1:
        t = "sample";
        break;
    case ....:
        ....;
}

System.out.println(t);

上記のようなコードだと、String t に対して final を付与できません。
そこで、以下のように書き換えます。

sample1.java
// 条件が多いならメソッドに切り分けてしまう
private static String initT(int x) {
    if(x == 0) return = "test";
    if(x > 0) return = "sample";
    if....
    return "";
}
//....
final String t = initT(x);

あるいは、条件が少ないなら、三項演算子を用いて、

sample1.java
//....
final String t = (x == 0) ? "test" : (x > 0) ? "sample" : "";

このように変数の初期化を単文にすることで、 final の付与を可能にできます。


私は上記のような書き換えを意識していますが、これは推奨されないもっと良い記述がある などあれば、コメント頂ければ幸いです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8