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?

【リファクタリング】Remove Control Flag(制御フラグの削除)

Posted at

1. 概要(Overview)

Remove Control Flag とは、
ループや条件分岐で「処理を終了させるための制御フラグ変数」を使っている場合に、
それを break / return / 例外処理 に置き換えてシンプルにするリファクタリングです。

制御フラグはコードを複雑にし、意図を分かりにくくします。
→ 直接的な制御構文を使った方が 読みやすく、安全 です。


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

  • ループの中で「フラグ変数」で処理を制御している
  • 条件を満たすとフラグを true/false にしてループを抜ける構造になっている
  • ループや条件式が フラグ変数に依存して読みにくい

3. 手順(Mechanics / Steps)

  1. 制御フラグを使っている箇所を特定
  2. フラグの役割を break / return / continue / 例外 に置き換える
  3. フラグ変数を削除
  4. 動作確認(副作用や複数条件に注意)

4. Kotlin 例(Before → After)

Before:制御フラグを使ったコード

fun findCustomer(customers: List<Customer>, targetId: Int): Customer? {
    var found: Customer? = null
    var flag = false

    for (c in customers) {
        if (!flag && c.id == targetId) {
            found = c
            flag = true
        }
    }
    return found
}
  • flag が「もう見つかったかどうか」を管理している
  • ロジックが冗長で意図が分かりにくい

After①:break を使用

fun findCustomer(customers: List<Customer>, targetId: Int): Customer? {
    var found: Customer? = null
    for (c in customers) {
        if (c.id == targetId) {
            found = c
            break
        }
    }
    return found
}

After②:return を使用(さらにシンプルに)

fun findCustomer(customers: List<Customer>, targetId: Int): Customer? {
    for (c in customers) {
        if (c.id == targetId) return c
    }
    return null
}

After③:Kotlin らしく firstOrNull を使う

fun findCustomer(customers: List<Customer>, targetId: Int): Customer? =
    customers.firstOrNull { it.id == targetId }

→ 制御フラグがなくなり、短く直感的なコード になった。


5. 効果(Benefits)

  • 制御フラグを排除して コードがシンプルに
  • 意図が直接的に表現され、可読性が向上
  • ループや条件式のロジックを理解しやすくなる
  • Kotlin なら標準ライブラリ関数でさらに短縮可能

6. 注意点(Pitfalls)

  • フラグが「複数条件を統合する役割」を持っている場合は単純に削除できない
  • 早期リターンを多用しすぎると逆に読みにくくなる場合もある
  • チームのコーディング規約(ガード節の好みなど)に合わせる

まとめ

  • Remove Control Flag は制御フラグを削除して break / return で直接表現するリファクタリング
  • 効果:可読性・明快さ・保守性 の向上
  • 基本思想:フラグ変数ではなく「直接的な制御構文」で意図を表す

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?