lundi 26 novembre 2018

Javascript - Refactoring if..else statements (ES6)

now I am trying to refactor my lots of if..else statements.

My code:

let condition = 'hi';

if(condition === 'hi'){
  commonFunction('hi');
  console.log('hi is called');

}else if(condition === 'bye'){
  commonFunction('bye');
  console.log('bye is called');

}else if(condition.includes('happy')){
  commonFunction('happy');
  console.log('happy is called');

}else if(condition === 'greeting'){
  commonFunction('greeting');
  console.log('greeting is called');

}

Refactored Code:

if(condition === 'hi'){
  hi();
}else if(condition === 'bye'){
  bye();
}else if(condition.includes('happy')){
  happy();
}else if(condition === 'greeting'){
  greeting();
}

function hi(){
  commonFunction('hi');
  console.log('hi is called');
}

function bye(){
  commonFunction('bye');
  console.log('bye is called');
}

function happy(){
  commonFunction('happy');
  console.log('happy is called');
}

function greeting(){
  commonFunction('greeting');
  console.log('greeting is called');
}

Is it better to declare each functions by condition like my refactored code???

Or, How about make class and call commonFunction by constructor? (I think switch..case is not useful becasue I have a condition that has includes() )

Aucun commentaire:

Enregistrer un commentaire