Refactoring 014 - Remove IF
Tags: webdev, beginners, programming, java
Published: 2024-07-05 16:38:37

*The first instruction you learned should be the least you use*

> TL;DR: Remove all your Accidental IF-sentences

# Problems Addressed

- Code Duplication

- Possible Typos and defects

# Related Code Smells

{% post https://dev.to/mcsee/code-smell-07-boolean-variables-3koj %}

{% post https://dev.to/mcsee/code-smell-36-switch-case-elseif-else-if-statements-h6c %}

{% post https://dev.to/mcsee/code-smell-133-hardcoded-if-conditions-53bi %}

{% post https://dev.to/mcsee/code-smell-156-implicit-else-1ko3 %}

{% post https://dev.to/mcsee/code-smell-119-stairs-code-1e2b %}

{% post https://dev.to/mcsee/code-smell-145-short-circuit-hack-4l4p %}

{% post https://dev.to/mcsee/code-smell-101-comparison-against-booleans-3aic %}

{% post https://dev.to/mcsee/code-smell-45-not-polymorphic-388g %}

# Steps

1. Find or Create a Polymorphic Hierarchy

2. Move the Body of Each IF to the Corresponding Abstraction

3. Name the Abstractions

4. Name the Method

5. Replace if Statements with Polymorphic Message Sends

# Sample Code

## Before

[Gist Url]: # (https://gist.github.com/mcsee/ffba17263f40053ed57698d0880b942c)

```java
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. */
```

## After

[Gist Url]: # (https://gist.github.com/mcsee/2c97cd57dc9e98c877e91fcb7ed3191c)

```java
// 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<String, MicrophoneState> 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();
    }
```

# Type

[X] Semi-Automatic

# Safety

Most steps are mechanic. This is a pretty safe refactoring

# Why is the code better?

The refactored code follows the open/closed principle and favors polymorphism instead of using IFs

# Limitations

You should only apply it to [**Accidental IFs**](https://dev.to/mcsee/how-to-get-rid-of-annoying-ifs-forever-1jfg).

Leave the business rules as **"domain ifs"** and don't apply this refactoring

# Tags

- IFs

# Related Refactorings

{% post https://dev.to/mcsee/refactoring-013-remove-repeated-code-4npi %}

# See also

{% post https://dev.to/mcsee/how-to-get-rid-of-annoying-ifs-forever-1jfg %}

# Credits

Image by <a href="https://pixabay.com/users/renuagra-5667962/">Renuagra</a> on <a href="https://pixabay.com/">Pixabay</a>

* * * 

This article is part of the Refactoring Series.

{% post https://dev.to/mcsee/how-to-improve-your-code-with-easy-refactorings-2ij6 %}