DEV Community

Cover image for How do you write codes for conditional statement?
Shin
Shin

Posted on

How do you write codes for conditional statement?

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.

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 ;(');
}
Enter fullscreen mode Exit fullscreen mode

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.

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;
}
Enter fullscreen mode Exit fullscreen mode

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)

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;
}
Enter fullscreen mode Exit fullscreen mode

It is possible to forget break when you add new condition, and the logic tends to be big if you use switch case.

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;
}
Enter fullscreen mode Exit fullscreen mode

(dictionary)

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);
Enter fullscreen mode Exit fullscreen mode

If new weekday should be added, it is easy to add it and to keep the maintainability.

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);
Enter fullscreen mode Exit fullscreen mode

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.

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)
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

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)
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

However, strategy pattern enables to write the readable and maintainable codes.
In strategy pattern, interface is used.

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
    }
}
Enter fullscreen mode Exit fullscreen mode

The class diagram
class diagram of strategy pattern

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.
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
    }
}
Enter fullscreen mode Exit fullscreen mode

Hope you enjoy a good life with conditional statements!

References

Top comments (0)