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 Duplicate Conditional Fragments(条件分岐内の重複処理の統合)

Last updated at Posted at 2025-09-22

1. 概要(Overview)

Consolidate Duplicate Conditional Fragments とは、
if-else / when の分岐ごとに 同じ処理が重複して書かれている場合、その共通部分を外にまとめるリファクタリング です。

ポイントは「分岐の中で繰り返されているコードを一箇所に統合する」こと。


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

  • 複数の分岐条件で 同じ処理 を繰り返している
  • 分岐後に必ず実行される処理があるのに、各ブロックに重複記述されている
  • 将来的に修正するときに 変更漏れが発生するリスク がある

3. 手順(Mechanics / Steps)

  1. if-else / when の各分岐を確認し、重複処理を探す
  2. 共通の処理を分岐外に移動
  3. 処理の順序に依存しないか確認(副作用・早期リターンに注意)
  4. 必要に応じてメソッド抽出して名前を付ける

4. Kotlin 例(Before → After)

Before:分岐ごとに重複処理

fun processOrder(order: Order) {
    if (order.isCancelled) {
        println("Order is cancelled")
        sendNotification(order.customer)
    } else if (order.isCompleted) {
        println("Order is completed")
        sendNotification(order.customer)
    } else {
        println("Order is pending")
        sendNotification(order.customer)
    }
}
  • どの分岐でも sendNotification(order.customer) を実行している
  • 共通処理が 3回繰り返されている

After①:共通処理を統合

fun processOrder(order: Order) {
    if (order.isCancelled) {
        println("Order is cancelled")
    } else if (order.isCompleted) {
        println("Order is completed")
    } else {
        println("Order is pending")
    }
    sendNotification(order.customer)
}

→ 重複していた処理が一箇所にまとまり、保守性が向上。


After②:メソッド抽出でさらに明確化

fun processOrder(order: Order) {
    printStatus(order)
    sendNotification(order.customer)
}

private fun printStatus(order: Order) {
    when {
        order.isCancelled -> println("Order is cancelled")
        order.isCompleted -> println("Order is completed")
        else -> println("Order is pending")
    }
}

→ 状態表示と通知が明確に分離され、読みやすくなった。


5. 効果(Benefits)

  • 重複コード削減 → 変更漏れ防止・保守性向上
  • コードの意図が明快に
  • 共通処理を一箇所に集めることで 自己文書化コード に近づく

6. 注意点(Pitfalls)

  • 分岐後に 異なる処理が必要なケース に無理に統合しない
  • 共通処理を外に出すと 実行順序が変わる 可能性がある(副作用に注意)
  • 早期リターン(return)や例外処理が絡む場合は特に注意

まとめ

  • Consolidate Duplicate Conditional Fragments は「条件分岐の中の重複処理」を統合するリファクタリング
  • 効果:重複排除、修正漏れ防止、保守性アップ
  • 基本思想:同じ処理は一度だけ書き、意図を明確にする

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?