リファクタリング 014 – IF を削除する方法

in Vlog

最初に学んだ指示は、あまり使わないようにするべきです。

TL;DR: 偶発的なIF文をすべて削除する

対処された問題

  • 誤字や欠陥の可能性

コードの臭い 07 – ブール変数

コードスメル 36 – Switch/case/elseif/else/if ステートメント

コード臭 133 – ハードコードされた IF 条件

コードの臭い 156 – 暗黙の Else

コードスメル 119 – 階段コード

コードスメル 145 – ショートサーキットハック

コード臭 101 – ブール値との比較

コードスメル 45 – ポリモーフィックではない

手順

  1. 多態的階層を検索または作成します。

  2. 各 IF の本体を対応する抽象化に移動します。

  3. 抽象化に名前を付けます。

  4. メソッドに名前を付けます。

  5. if ステートメントをポリモーフィック メッセージ送信に置き換えます。

サンプルコード

前に

public String handleMicrophoneState(String state) {
    if (state.equals("off")) {
        return "Microphone is off";
    } else {
        return "Microphone is on";
    }
}

/* The constant representing the 'off' state is
duplicated throughout the code, 
increasing the risk of typos and spelling mistakes. 
The "else" condition doesn't explicitly check for the 'on' state;
it implicitly handles any state that is 'not off'. 
This approach leads to repetition of the IF condition
wherever the state needs handling, 
exposing internal representation and violating encapsulation.
The algorithm is not open for extension and closed for modification,
meaning that adding a new state 
will require changes in multiple places in the code. */

// Step 1: Find or Create a Polymorphic Hierarchy

abstract class MicrophoneState { }
final class On extends MicrophoneState { }
final class Off extends MicrophoneState { }

// Step 2: Move the Body of Each IF to the Corresponding Abstraction

abstract class MicrophoneState {
    public abstract String polymorphicMethodFromIf();
}

final class On extends MicrophoneState {
    @Override
    public String polymorphicMethodFromIf() {
        return "Microphone is on";
    }
}

final class Off extends MicrophoneState {
    @Override
    public String polymorphicMethodFromIf() {
        return "Microphone is off";
    }
}

// Step 3: Name the Abstractions

abstract class MicrophoneState {}
final class MicrophoneStateOn extends MicrophoneState {}
final class MicrophoneStateOff extends MicrophoneState {}

// Step 4: Name the Method

abstract class MicrophoneState {
   public abstract String handle();
}

final class MicrophoneStateOn extends MicrophoneState {
    @Override
    String handle() {
        return "Microphone is on";
    }
}

final class MicrophoneStateOff extends MicrophoneState {
    @Override
    String handle() {
        return "Microphone is off";
    }
}

// Step 5: Replace if Statements with Polymorphic Message Sends

 public String handleMicrophoneState(String state) {
        Map states = new HashMap();
        states.put("muted", new Muted());
        states.put("recording", new Recording());
        states.put("idle", new Idle());

        MicrophoneState microphoneState = 
            states.getOrDefault(state, new NullMicrophoneState());
        return microphoneState.handle();
    }

タイプ

安全性

ほとんどのステップは機械的です。これはかなり安全なリファクタリングです。

なぜコードの方が優れているのでしょうか?

リファクタリングされたコードはオープン/クローズ原則に従い、IF を使用する代わりにポリモーフィズムを優先します。

制限事項

適用できるのは 偶然のIF

ビジネスルールはそのままにしておく 「ドメインif」 このリファクタリングは適用しないでください。

参照


この記事はリファクタリング シリーズの一部です。

簡単なリファクタリングでコードを改善する方法

関連記事

前の投稿
TypeScript SDK 開発: 5 歳児でもステップバイステップで理解できる ~ パート 1: 最初の MVP
次の投稿
HDR 主観テスト ワークフローの検証に関する推奨事項: 概要と概要