0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【リファクタリング】Consolidate Conditional Expression(条件式の統合)

Posted at

1. 概要(Overview)

Consolidate Conditional Expression は、
同じ結果を返す複数の条件分岐をひとつにまとめるリファクタリング です。

複数の if が同じ処理を返している場合、
条件式を統合することで 冗長さをなくし、意図を明確に できます。


2. 適用シーン(When to Use)

  • 複数の if / when同じ処理 をしている
  • 条件が重複しており、将来の変更で 修正漏れ のリスクがある
  • 「週末か休日なら給料ゼロ」など、ひとつの意味的ルール を複数の条件に分割して書いている

3. 手順(Mechanics / Steps)

  1. 複数の条件分岐の中に「同じ処理」を見つける
  2. 条件を論理演算子(||, &&)でまとめる
  3. 共通処理をひとつのブロックにまとめる
  4. 必要に応じて条件式を メソッド抽出(Extract Method) して名前をつける

4. Kotlin 例(Before → After)

Before:条件が分散

fun getPayAmount(isDead: Boolean, isSeparated: Boolean, isRetired: Boolean): Int {
    if (isDead) return 0
    if (isSeparated) return 0
    if (isRetired) return 100
    return 200
}
  • isDeadisSeparated が同じ結果を返している
  • 意図が分散していて読みづらい

After①:条件式を統合

fun getPayAmount(isDead: Boolean, isSeparated: Boolean, isRetired: Boolean): Int {
    if (isDead || isSeparated) return 0
    if (isRetired) return 100
    return 200
}

→ 「死亡または退職済みなら 0」という意図が ひとつの条件にまとまった


After②:メソッド抽出で自己説明的に

fun getPayAmount(isDead: Boolean, isSeparated: Boolean, isRetired: Boolean): Int {
    if (isNotEligible(isDead, isSeparated)) return 0
    if (isRetired) return 100
    return 200
}

private fun isNotEligible(isDead: Boolean, isSeparated: Boolean) =
    isDead || isSeparated

isNotEligible という名前で、ビジネスルールの意図がより明確になった。


5. 効果(Benefits)

  • 条件式の重複がなくなり、修正漏れのリスクを防止
  • コードが短く明快に → 可読性向上
  • 「ビジネスルール」をひとつの表現にまとめられる
  • 意図を名前で表現でき、自己文書化コード になる

6. 注意点(Pitfalls)

  • 複雑な条件を無理にまとめると、かえって読みにくくなる
  • 「統合したほうが意味が伝わるか?」を常に確認
  • 複雑なビジネスルールの場合は、ポリモーフィズム(Replace Conditional with Polymorphism) を検討する

まとめ

  • Consolidate Conditional Expression は「同じ結果を返す条件」をまとめるリファクタリング
  • メリット:重複除去・意図の明確化・保守性向上
  • 基本思想:条件式は「意味単位でまとめて、意図が伝わる形」に整理する

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?