如何在功能之间共享逻辑?

时间:2017-12-13 18:18:51

标签: javascript design-patterns coding-style

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

示例:

以下函数包含相同的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();
}

3 个答案:

答案 0 :(得分:4)

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

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中那样的包装器)等等。

答案 1 :(得分:0)

一种简单的方法是将操作作为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();
}

答案 2 :(得分:0)

你的if / else是一个类型(hirer)的开关。因此,你可以Force browser to clear cache。您需要第二个函数的名称,我猜determineHiringRate()(虽然我不确定这是正确的名称)。

这是解决方案的类图:

Replace conditional with polymorphism