【问题标题】:Javascript - Refactoring if..else statements (ES6)Javascript - 重构 if..else 语句 (ES6)
【发布时间】:2018-11-27 02:45:38
【问题描述】:

我正在尝试重构 if..else 语句。

我的代码:

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');

}

重构代码:

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');
}

像我重构的代码那样按条件声明每个函数更好吗???

或者,创建类并通过构造函数调用 commonFunction 怎么样? (我认为 switch..case 没有用,因为我有一个包含 includes() 的条件)

【问题讨论】:

  • @lucumt 我的情况有 includes() 所以我想我不能使用 switch
  • 这实际上与您的函数的动态程度有关。在您的示例中,您可以只声明 1 个函数并传递 2 个参数。您也可以通过字符串调用函数:stackoverflow.com/a/1144334/10412708
  • 在上述情况下,我们不能像下面那样做吗? const functionToCall = condtion.includes('hello') ? '你好' : 条件;组件(函数调用);

标签: javascript if-statement design-patterns refactoring conditional-statements


【解决方案1】:

我建议将所有这些if-elses 移动到commonFunction 本身(如果它不再包含相同的if-elses,如果它确实需要更复杂的重构):

const commonFunction = (condition) => {
  let f = ['hi', 'bye', 'happy', 'greeting'].find(e => condition.includes(e))
  console.log(f + ' is called');
  if (!f) return;
  // do something
  // return the result if needed
}

commonFunction('greeting')
commonFunction('die')

【讨论】:

    【解决方案2】:

    对此可以做的一件事是使用conditionobject 中的函数声明为keys

    let objFunc = {
        'hi': function() {
           commonFunction('hi');
           console.log('hi is called');
        },
        'happy': function() {
           commonFunction('happy');
           console.log('happy is called');
        },
        'bye': function() {
           commonFunction('bye');
           console.log('bye is called');
        },
        'greeting': function() {
           commonFunction('greeting');
           console.log('greeting is called');
        },
    };
    
    
    objFunc[condition]();
    

    【讨论】:

    • 但是,我有条件使用includes()...在这种情况下如何使用条件作为键?
    【解决方案3】:

    一种选择是使用包含函数的对象,而不是使用多个独立函数。然后,只需使用属性查找。

    不过,对于这个确切的代码,您可以通过使用 Proxy 来检查访问了哪个属性,而不是拥有多个属性(因为您的所有属性/函数都有共同的功能),从而使其更加干燥:

    const condition = 'hi';
    
    const fns = new Proxy({}, { get: (_, prop) => {
      console.log(prop + ' is called');
    }});
    
    const props = ['hi', 'bye', 'greeting'];
    if (condition.includes('happy')) {
      fns.happy();
    } else if (fns[condition]) {
      fns[condition]();
    }

    这是非常干的,但做起来很奇怪——在大多数情况下,你会使用一个对象来代替:

    const fns = {
      hi() {
        console.log('hi is called');
      },
      bye() {
        console.log('bye is called');
      },
      greeting() {
        console.log('greeting is called');
      },
      happy() {
        console.log('happy is called');
      }
    }
    
    const condition = 'hi';
    
    if (condition in fns) {
      fns[condition]();
    } else if (condition.includes('happy')) {
      fns.happy();
    }

    【讨论】:

      【解决方案4】:

      在您的原始代码中,您编写了多个 if else 语句,只是为了使用不同的预定义参数调用相同的函数,所以不要按照您的方式进行重构, 我认为这是更容易和更小的代码。

      let predefinedArgs = {
          hi: 'hi',
          bye: 'bye'
          ...
      }
      
      let condition = 'hi'
      commonFunction(predefinedArgs[`condition`]);
      

      【讨论】:

      • 但是,我有条件使用includes()...在这种情况下如何使用条件作为键?
      • 您有条件使用includes() 意味着什么,请告诉我,我没有得到任何问题?
      【解决方案5】:

      你有一组条件,你想调用一个通用函数。最好的方法是简单地测试您是否可以处理这种情况(这就是您可以使用includes 的地方)。然后调用该函数。

      const allowed = ['hi', 'bye', 'happy', 'greeting']
      
      let condition = 'happy'
      
      if (allowed.includes(condition)) {           // do you know how to deal with condition? 
        commonFunction(condition)                 // if so call the function
      } else {
        console.log(`unknown condition ${condition}`) // otherwise log an error
      }
      
      // not sure what commonFunction does, so this is just for the example
      function commonFunction(condition) {
        console.log(`${condition} is called`);
      }

      【讨论】:

      • happy 不同于其他:else if(condition.includes('happy'))
      【解决方案6】:

      我认为所有解决方案都应该可以正常工作。对于包含的条件,也许您可​​以尝试添加一个新参数。 我的意思是,如前面的答案所述:

        let f = ['hi', 'bye', 'happy', 'greeting'].find(e => condition.includes(e))
        console.log(f + ' is called');
        if (!f) return;
        // do something
        // return the result if needed
      }
      
      commonFunction('greeting')
      commonFunction('die')```
      
      This could be converted to :
      ```const commonFunction = (condition, functionName) => {
      // ... other code
      // and then use can use the following link to call the function which you want to execute`
      https://stackoverflow.com/questions/53492013/javascript-refactoring-if-else-statements-es6/53492079
      const young = () => {//...}
      and the calling could be:
      commonFunction('greeting', slice)
      commonFunction('die', young)```
      
      Hope this makes sense!
      

      【讨论】:

        猜你喜欢
        • 2021-04-11
        • 2021-09-11
        • 2016-06-21
        • 2015-05-16
        • 2016-11-21
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        相关资源
        最近更新 更多