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?

【リファクタリング】Decompose Conditional(条件式の分解)

Posted at

1. 概要(Overview)

Decompose Conditional とは、
複雑な条件式や分岐処理を 明示的なメソッドや変数に分解 して、コードを読みやすくするリファクタリングです。

目的:

  • 長大で複雑な if-else / when を理解しやすくする
  • 条件や処理の意図を名前に表すことで、自己文書化コード にする

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

  • 条件式が長く、読みにくい
  • if / when の分岐に 複雑な式 が直接書かれている
  • 分岐ごとの処理もごちゃ混ぜになっている

「条件式が何を意味しているか一目で分からない」ときが適用のサイン。


3. 手順(Mechanics / Steps)

  1. 条件式の各部分を メソッドまたは説明変数 に抽出
  2. 分岐ごとの処理も可能なら メソッド抽出 する
  3. if-else / when の中身を「名前」で説明できる状態にする

4. Kotlin 例(Before → After)

Before:条件式が複雑で読みにくい

fun payAmount(employee: Employee): Int {
    if (employee.isSeparated || employee.isRetired) {
        return 0
    } else {
        if (employee.isPartTime) {
            return employee.rate * employee.hours
        } else {
            return employee.salary
        }
    }
}
  • 条件が直接ベタ書きされていて意図が分かりにくい

After:条件式を分解

fun payAmount(employee: Employee): Int {
    return when {
        isNotEligibleForPay(employee) -> 0
        isPartTime(employee) -> partTimePay(employee)
        else -> fullTimePay(employee)
    }
}

private fun isNotEligibleForPay(e: Employee) = e.isSeparated || e.isRetired
private fun isPartTime(e: Employee) = e.isPartTime
private fun partTimePay(e: Employee) = e.rate * e.hours
private fun fullTimePay(e: Employee) = e.salary

when の各分岐が「名前付き条件」と「名前付き処理」になり、読みやすさ大幅向上。


5. 効果(Benefits)

  • 条件式の意図が「名前」で説明される → 理解が容易に
  • 分岐ごとの処理を 独立してテスト可能
  • 変更に強くなる(分岐の追加・変更が容易)
  • コメント不要で「自己説明的コード」になる

6. 注意点(Pitfalls)

  • 単純な条件まで過剰に分解すると逆に冗長化
  • 名前の付け方が曖昧だと逆に読みにくくなる
  • 戦略パターン(Strategy)やポリモーフィズムで置き換えた方がよいケースもある

まとめ

  • Decompose Conditional は複雑な条件式を「名前付きの小さなメソッドや変数」に分解するリファクタリング
  • 効果:読みやすさ・テスト容易性・保守性 の向上
  • 基本思想:条件式は「意図を名前で説明」できる形に整理する

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?