DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
stemmlerjs profile image
Khalil Stemmler

I only use switch statements in two scenarios:

A: I'm using an Abstract Factory for something.

public class PokemonFactory {
  public static createPokemon (type: PokemonType): Pokemon {
    switch (type) {
       case 'pikachu':
         return new Pikachu();
       case 'charizard':
         return new Charizard();
       case 'squirtle':
         return new Squirtle();
       default:
         return null;
    }
  } 
}

B: If I'm writing reducers in redux

   switch (action) {
     case actions.FETCHING_PROFILE:
     case actions.FETCHING_PROFILE_SUCCESS:
     case actions.FETCHING_PROFILE_FAILURE:
     case actions.SUBMITTING_PROFILE:
     case actions.SUBMITTING_PROFILE_SUCCESS:
     case actions.SUBMITTING_PROFILE_FAILURE:
        return { ...state, profile: profileReducer(state.profile, action);
     default:
        return state;
  }

Imagine the OR pipes if that last one was made using if statements. Being able to match many cases at one time saves so much typing.