【问题标题】:How to share logic among functions?如何在函数之间共享逻辑?
【发布时间】:2017-12-13 18:18:51
【问题描述】:

我在开发代码中包含一些类似块的代码时遇到了一个问题。我的问题是:在函数之间共享逻辑的最佳方法是什么?

例子:

以下函数包含相同的 if/else 逻辑。我们如何重构这段代码以获得更简洁和可维护的代码?

// pseudo code...

const hirer = 'woman';

const getPositions = () => {
 if (hirer === 'woman') {
   getPositionsFromWomen();
   // do other stufs here...
 } else if (hirer === 'man') {
   getPositionFromMen();
   // do other stufs here...
 }
 // maybe other stufs here...
}


const hire = (hirer) => {
  if (hirer === 'woman') {
    increaseWomenHiringRate(hirer);
    // do other stufs here...
  } else if (hirer === 'man') {
    increaseMenHiringRate(hirer);
    // do other stufs here...
  }
 setPositionClosed();
}

【问题讨论】:

    标签: javascript design-patterns coding-style


    【解决方案1】:

    一种相当标准的方法是参数化逻辑。在这种情况下,也许通过将逻辑放在一个接受函数的函数中,它将为每个逻辑分支调用:

    const hirer = 'woman';
    
    const hirerDispatch = (hirer, ifWoman, ifMan) => hirer === 'woman' ? ifWoman() : ifMan();
    
    const getPositions = () => {
      hirerDispatch(hirer, getPositionsFromWomen, getPositionFromMen);
      // maybe other stuff here...
    };
    
    const hire = (hirer) => {
      hirerDispatch(hirer, () => increaseWomenHiringRate(hirer), () => increaseMenHiringRate(hirer));
      setPositionClosed();
    };
    

    更复杂的参数化可能涉及传递具有分支函数属性的对象,包括要传递的参数(因此我们不需要像 hire 中那样的包装器)等等。

    【讨论】:

      【解决方案2】:

      一种简单的方法是将操作作为 Javascript 对象作为参数传递给包含逻辑的方法。这就是您的代码的样子:

      const hirer = 'woman';
      
      var positionHire = {
          women: getPositionsFromWomen,
          men: getPositionsFromMen
      }
      const getPositions = (hirer, positionHire) => {
       if (hirer === 'woman') {
         getPositionsFromWomen();
         // do other stufs here...
       } else if (hirer === 'man') {
         getPositionFromMen();
         // do other stufs here...
       }
       // maybe other stufs here...
      }
      
      var hireRate = {
          women: increaseWomenHiringRate,
          men: increaseMenHiringRate
      }
      
      const hire = (hirer, hireRate) => {
        if (hirer === 'woman') {
          increaseWomenHiringRate(hirer);
          // do other stufs here...
        } else if (hirer === 'man') {
          increaseMenHiringRate(hirer);
          // do other stufs here...
        }
       setPositionClosed();
      }
      

      【讨论】:

        【解决方案3】:

        您的 if/else 是一种类型 (hirer) 的开关。因此,您可以Replace conditional with polymorphism。您需要为第二个函数命名,我猜它是 determineHiringRate()(尽管我不确定这是正确的名称)。

        这是解决方案的类图:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-22
          • 2014-01-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多