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?

【リファクタリング】Simplifying Conditional Expressions(条件式の単純化)

Posted at

はじめに

Simplifying Conditional Expressions は、
複雑で読みにくい条件式を整理し、コードの意図を明確にする リファクタリング群です。

条件式はビジネスルールを表現する中心的な部分ですが、
長大な if / when / ネスト構造に埋もれると理解が困難になります。

このカテゴリは、複雑な条件を「短く・明快に・自己説明的に」書き直す ことを目的としています。


代表的なテクニック

1. Decompose Conditional(条件式の分解)

  • 複雑な条件式をメソッドや説明変数に抽出する

  • 例:「if (date.before(SUMMER_START) || date.after(SUMMER_END)) → if (isNotSummer(date))」

2. Consolidate Conditional Expression(条件式の統合)

  • 同じ結果を返す複数の条件をひとつにまとめる

  • 例:「if (isWeekend) return 0; if (isHoliday) return 0; → if (isWeekend || isHoliday) return 0;」

3. Consolidate Duplicate Conditional Fragments(条件分岐内の重複処理の統合)

  • if-else それぞれに同じ処理がある場合、それを外に出す

4. Remove Control Flag(制御フラグの削除)

  • ループ中に「フラグ変数」で処理を制御している場合、break / return などに置き換える

5. Replace Nested Conditional with Guard Clauses(入れ子条件をガード節に置換)

  • ネストした条件を「早期リターン」で整理する

6. Replace Conditional with Polymorphism(条件式をポリモーフィズムに置換)

  • 条件分岐が「型ごとの処理」なら、サブクラスや Strategy パターンに置き換える

Kotlin 例

Before:複雑な条件式

fun getPayAmount(isDead: Boolean, isSeparated: Boolean, isRetired: Boolean): Int {
    var result: Int
    if (isDead) {
        result = 0
    } else {
        if (isSeparated) {
            result = 0
        } else {
            if (isRetired) {
                result = 100
            } else {
                result = 200
            }
        }
    }
    return result
}

After①:Guard Clauses で単純化

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

After②:条件式の統合

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

→ ネストが解消され、条件の意図がすぐ理解できる。


注意点

  • 単純化しすぎて条件の意味が失われるリスク

  • ビジネスルールの表現力を下げないよう、適切な命名 が重要

  • 多態化に置き換える場合は、オーバーエンジニアリングに注意


まとめ

  • Simplifying Conditional Expressions は条件式を明快に整理するリファクタリング群

  • 代表手法:Decompose Conditional / Consolidate Conditional / Guard Clauses / Polymorphism

  • 基本思想:条件式は「短く・明快に・自己説明的に」

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?