How do you write codes for conditional statement?
Tags: if, switch, dictionary, strategy
Published: 2022-06-28 02:34:36

---
title: How do you write codes for conditional statement?
published: true
description: the patterns of conditional statements
tags: if, switch, dictionary, strategy
cover_image: https://www.silhouette-illust.com/wp-content/uploads/2017/01/joukenbun_22600-300x300.jpg
---

## About this post
When we use `if` statement in the conditional logic, the indentation will be deep, which makes difficult to read the code.
In this post, the other types of implementation for the conditional logic will be introduced.
I would like every developer to get other ideas apart from `if` statement for the condition and to write the code which is easy to maintain.

## Target readers
* the beginners who just started the development
* the ones who want to know how to handle complicated conditional statement
* the ones who reviews codes in the development team

## conditional statements
In this post, the four types of implementation for the conditional statement are introduced.
* if / if-else
* switch case
* dictionary
* strategy pattern

If you know other ways of implementation apart from the ways introduced in this post, I will be happy that you will share by comment.

## if / if-else
`if/if-else` will be preferable if the condition includes some expressions like `<=`, `>=` or `!` and the logic inside the `if` statement is not so big.
```javascript
const examinationScore = doExamination();
if (examinationScore >= 80) {
  // not so big logic
  console.log('good job :)');
} else if (examinationScore >= 60) {
  // not so big logic
  console.log('so so :()');
} else {
  // not so big logic
  console.log('do more hardwork ;(');
}
```
Note that you can use strategy pattern which is mentioned later if the logic inside the `if` statement is big, because...
* hard to memorize what is the condition of the logic inside the `if` statement (hard to read the codes)
* hard to maintain the codes

## switch case
You can choose `switch case` statement if the number of conditions is increased.
```javascript
const gpaScore = getGPA();
switch (gpaScore) {
  case 2:
    // do some small logic
    break;
  case 3:
    // do some small logic
    break;
  case 4:
    // do some small logic
    break;
  case 5:
    // do some small logic
    break;
  default:
    // do some small logic
    break;
}
```
Note that you can use dictionary which is mentioned below when **some value** is returned under the specific condition.

## dictionary
If you wanna write `switch case` like the below, you can consider to use dictionary instead.
It is suitable to use dictionary when **some value** is returned under the specific condition.

(switch)
```javascript
const weekdayName = getWeekday();
switch (weekdayName) {
  case 'monday':
    console.log('Let\'s start a new week!');
    break;
  case 'tuesday':
    console.log('This is second day of this week. Do your best!');
    break;
  case 'wednesday':
    console.log('If you need, let\'s take break');
    break;
  case 'thursday':
    console.log('The half of the week done!');
    break;
  case 'friday':
    console.log('If you do your best today, tomorrow is holiday!');
    break;
}
```
It is possible to forget `break` when you add new condition, and the logic tends to be big if you use `switch case`.
```javascript
const weekdayName = getWeekday();
switch (weekdayName) {
  case 'sunday':
    console.log('Hoo! Today is holiday!'); // oops! if you forget "break", it makes some bugs!
  case 'monday':
    console.log('Let\'s start a new week!');
    break;
  case 'tuesday':
    console.log('This is second day of this week. Do your best!');
    break;
  case 'wednesday':
    console.log('If you need, let\'s take break');
    break;
  case 'thursday':
    console.log('The half of the week done!');
    break;
  case 'friday':
    console.log('If you do your best today, tomorrow is holiday!');
    break;
}
```

(dictionary)
```javascript
const weekdayMessages = {
  monday: 'Let\'s start a new week!',
  tuesday: 'This is second day of this week. Do your best!',
  wednesday: 'If you need, let\'s take break',
  thursday: 'The half of the week done!',
  friday: 'If you do your best today, tomorrow is holiday!'
};
const weekdayName = getWeekday();
const message = weekdayMessages[weekdayName];
console.log(message);
```
If new weekday should be added, it is easy to add it and to keep  the maintainability.
```javascript
const weekdayMessages = {
  // just add elements if you wanna add new weekday
  sunday: 'Hoo! Today is holiday!',
  monday: 'Let\'s start a new week!',
  tuesday: 'This is second day of this week. Do your best!',
  wednesday: 'If you need, let\'s take break',
  thursday: 'The half of the week done!',
  friday: 'If you do your best today, tomorrow is holiday!'
};
const weekdayName = getWeekday();
const message = weekdayMessages[weekdayName];
console.log(message);
```

## strategy pattern
If you use object oriented language (like Java, C# or Ruby), you can choose strategy pattern instead of `if / if-else` statement.

If you use `if / if-else` statement, the logic will be below
This is not easy to read and maintain the codes.
```java
public class FooHandler {
    public void doSomeLogic() {
      if (/*condition A*/) {
        // logic A (big logic)
      } else if (/*condition B*/) {
        // logic B (big logic)
      } else if (/*condition C*/) {
        // logic C (big logic)
      }
    }
}
```
If you wanna add logic D newly or change logic B, you need to change the logic of `FooHandler`.
As a result, you need to test the whole class of `FooHandler` again and again.
```java
public class FooHandler {
    public void doSomeLogic() {
      if (/*condition A*/) {
        // logic A (big logic)
      } else if (/*condition B*/) {
        // you need to edit FooHandler if you wanna modify logic B
        // logic B (big logic)
      } else if (/*condition C*/) {
        // logic C (big logic)
      } else if (/*condition D*/) {
        // you need to edit FooHandler if you wanna add logic D
        // logic D (big logic)
      }
    }
}
```

However, strategy pattern enables to write the readable and maintainable codes.
In strategy pattern, `interface` is used.
```java
public class Program {
    public static void main () {
        FooHandler handler = new FooHandler();
        // choose the class which you wanna execute
        handler.doSomeLogic('Bbb');
    }
}

public class FooHandler {
    public void doSomeLogic(String className) {
        // if statement is not need here
        IFoo hogeInstance = (IFoo) Class.forName(className).newInstance();
        String result = hogeInstance.execute();
    }
}

public interface IFoo {
    execute();
}

// if you wanna add / change / delete the logic, you just edit the individual class Aaa, Bbb or Ccc
public class Aaa implements IFoo {
    public void execute() {
        // logic A
    }
}

public class Bbb implements IFoo {
    public void execute() {
        // logic B
    }
}

public class Ccc implements IFoo {
    public void execute() {
        // logic C
    }
}
```
The class diagram
![class diagram of strategy pattern](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w255aoiolfqyilk9eow1.png)

The good point of strategy pattern is...
* easy to add or change the logic
(easy to add or change the logic of individual class `Aaa`, `Bbb`, `Ccc`, `Ddd`).
* no need to write `if / if-else`, so the logic will not be complicated.

```java
public class Program {
    FooHandler handler = new FooHandler();
    // choose the class which you wanna execute
    handler.doSomeLogic('Bbb');
}

public class FooHandler {
    public void doSomeLogic(String className) {
      // if statement is not need here
      IFoo hogeInstance = (IFoo) Class.forName(className).newInstance();
      String result = hogeInstance.execute();
    }
}

public interface IFoo {
    execute();
}

// if you wanna add / change / delete the logic, you just edit the individual class Aaa, Bbb or Ccc
public class Aaa implements IFoo {
    public void execute() {
        // logic A
    }
}

// if you wanna modify logic B, you just edit class BBb (no need to test again for other classes)
public class Bbb implements IFoo {
    public void execute() {
        // logic B
    }
}

public class Ccc implements IFoo {
    public void execute() {
        // logic C
    }
}

// if you wanna add new logic, you just add new class (no need to test again for other classes)
public class Ddd implements IFoo {
    public void execute() {
        // logic D
    }
}
```

Hope you enjoy a good life with conditional statements!

## References
* [Strategy pattern - Wikipedia](https://en.wikipedia.org/wiki/Strategy_pattern)