現場で役立つシステム設計の原則 〜変更を楽で安全にするオブジェクト指向の実践技法
「CHAPTER1 目的ごとに変数を用意する」の話題
やっていること
- ベース価格の計算
- 送料の加算
- 税額の加算
int price = quantity * unitPrice;
if (price < 3000)
price += 500;
price = price * taxRate();
ローカル変数priceが以下の3つの目的に使い回されている。
- 数量×単価の計算結果
- その計算結果に送料を加算した結果
- さらにその加算した結果に税率を適用した結果
1つの変数を複数の目的で使い回すとコードを読む際混乱する。読んで理解することが難しいので要件が変更したときにコードを変更することも難しい。 また、ローカル変数priceを使いまわすと変更の影響範囲が広がる。本来は関係のない箇所に影響する予想外の副作用を起こす可能性がある。
対策としては、変更の影響範囲を小さくしてわかりやすくするために、目的ごとに個々のローカル変数を用意する(説明用の変数の導入)
int basePrice = quantity * unitPrice; // 数量×単価
int shippingCost = 0; // 送料の初期値
if (basePrice < 3000)
shippingCost = 500; // 送料500円
int itemPrice = (basePrice + shippingCost) * taxRate(); // 税込み金額