ローカル変数への書き込みの倒し方

前回は

参照引数を、メソッドのシグネチャを変更することで消せることを示した。

今回は

これまた悪しきものとされることがある、ローカル変数への書き込み、つまり再代入を倒す方法を示したいと思う。

現在のコードは以下のようになっている。

Option Explicit On
Option Strict On
Option Infer On

Module Program
    Sub PrintApplePrice(applePrice As Integer)
        Console.WriteLine("{0}円", applePrice)
    End Sub

    Function UpdateApplePrice(price As Integer) As Integer
        Console.Write("{0}円から、", price)
        price = 80
        Console.WriteLine("{0}円に更新", price)
        Return price
    End Function

    Sub Main()
        PrintApplePrice(100)

        Dim price = 100
        price = UpdateApplePrice(price)

        PrintApplePrice(price)
    End Sub
End Module

price は 100 で初期化された後、UpdateApplePrice の返却値によって代入されている。ここの書き込みを消したい。

戦略は「新しい変数を宣言し、新しい値で初期化する」ことだ。

初期化がポイントで、変数を宣言した後に代入をするのではなく、変数の宣言時に初期化する。言葉の定義の話になるが、変数を宣言し直後に初期値を代入するのは初期化とは呼ばない。それは代入である。宣言時に値を設定するのが初期化である。

つまりこうする

    Sub Main()
        PrintApplePrice(100)

        Dim originalPrice = 100
        Dim updatedPrice = UpdateApplePrice(originalPrice)

        PrintApplePrice(updatedPrice)
    End Sub

updatedPrice を宣言し、UpdateApplePrice の返却値で初期化する。代入は一切行わない。PrintApplePrice には変更した price ではなく、新しい変数 updatedPrice を渡す。元の price は意味を明確にするために originalPrice へリネームした。

これでローカル変数への書き込みが消えた。ローカル変数は初期化し、その後は読み取りのみにする。

まとめ

ローカル変数への書き込みを消すことができた。

Option Explicit On
Option Strict On
Option Infer On

Module Program
    Sub PrintApplePrice(applePrice As Integer)
        Console.WriteLine("{0}円", applePrice)
    End Sub

    Function UpdateApplePrice(originalPrice As Integer) As Integer
        Console.Write("{0}円から、", originalPrice)
        Dim updatedPrice = 80
        Console.WriteLine("{0}円に更新", updatedPrice)
        Return updatedPrice
    End Function

    Sub Main()
        PrintApplePrice(100)

        Dim originalPrice = 100
        Dim updatedPrice = UpdateApplePrice(originalPrice)

        PrintApplePrice(updatedPrice)
    End Sub
End Module

次回は

標準出力と戦って倒す。


この記事が気に入ったらサポートをしてみませんか?