javascript - 如何重构一个很长的 else if 语句?

标签 javascript refactoring conditional-statements cyclomatic-complexity

我的代码片段达到了圈数限制,正在尝试想办法重构。

if(item.oldLabelType === 'Fruits') {
  item.newLabel = this._processFruitsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Vegetables') {
  item.newLabel = this._processVegetablesLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Animals') {
  item.newLabel = this._processAnimalsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Fish') {
  item.newLabel = this._processFishLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Birds') {
  item.newLabel = this._processBirdsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Colors') {
  item.newLabel = this._processColorsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Countries') {
  item.newLabel = this._processCountriesLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Drinks') {
  item.newLabel = this._processDrinksLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Cars' || item.oldLabelType === 'Airplanes') {
  item.newLabel = this._processTransportationLabel(item.oldLabel);
}

概要 - 我正在重构代码库,后端返回不需要的值,即某些东西的旧标签可能是“仅 1000 美元”,新标签需要“您今天只需支付 1000 美元”。标签操作完全不同,具体取决于发回的 item.oldLabelType。因此,我无法真正编写一个通用的函数来将所有旧标签转换为新标签。

该怎么办!?

最佳答案

这里通常的答案是:

  1. 使用开关(但这并没有太大的改进,或者可以说根本没有改进)
  2. 使用查找 map 或对象
  3. 使用字符串连接和方括号表示法

这是第三个的样子:

var functionName = item.oldLabelType === 'Cars' || item.oldLabelType === 'Airplanes'
    ? "_processTransportationLabel"
    : "_process" + item.oldLabelType + "Label";
if (this[functionName]) {
    item.newLabel = this[functionName](item.oldLabel);
}

关于javascript - 如何重构一个很长的 else if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801872/

相关文章:

javascript - While 循环和innerHTML

javascript - Jquery toggleclass 不起作用

javascript - 将日期时间从一个偏移量转换为另一个偏移量

language-agnostic - 为什么不在同一行声明多个相同类型的变量?

Java Date/Calendar 对象字符串,比较

JavaScript : repeat function not work

html - 将基于表格的 HTML 布局重构为 CSS 的工具?

java - 确定 Eclipse 中函数参数的适当父类型

Java:如何在for循环中将try-catch作为条件?

javascript - 如何为下面的代码创建一组新的列而不是行?