Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Last active August 14, 2019 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/52742bbf84a680e34e086cd3d5b9178a to your computer and use it in GitHub Desktop.
Save j5ik2o/52742bbf84a680e34e086cd3d5b9178a to your computer and use it in GitHub Desktop.

現場で役立つシステム設計の原則 〜変更を楽で安全にするオブジェクト指向の実践技法

「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(); // 税込み金額
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment