前端面试题之 如何减少项目里面 if-else【项目优化】

349 阅读2分钟

ifelse.png

当项目中存在大量的 if-else 语句时,可以考虑以下几种优化方法

  1. 策略模式

    • 创建一组策略对象,每个对象对应一种条件和处理逻辑。根据不同的条件选择相应的策略对象来执行操作。

    JavaScript 示例,展示了策略模式的使用

// 定义不同的策略函数
const strategies = {
  strategyA: function (num) {
    return num * 2;
  },
  strategyB: function (num) {
    return num + 10;
  },
  strategyC: function (num) {
    return num - 5;
  }
};

// 上下文对象,持有策略对象和操作数据
class Context {
  constructor(strategy) {
    this.strategy = strategy;
  }

  executeStrategy(num {
    return strategies[this.strategy](num);
  }
}

// 使用示例
const contextA = new Context('strategy');
console.log(contextA.executeStrategy(5));  // 输出 10

const contextB = new Context('strategyB');
console.log(contextB.executeStrategy(5));  // 输出 15

const contextC = new Context('strategyC');
console.log(contextC.executeStrategy(5));  // 输出 0

  1. 表驱动法

    • 建立一个数据结构(如对象或数组),将条件与对应的处理函数或值关联起来,通过查找表来获取相应的处理方式。
const handlers = {
  condition1: () => {
    // 处理条件 1 的逻辑
  },
  condition2: () => {
    // 处理条件 2 的逻辑
  },
  // 更多条件和处理函数
};

const condition = "condition1"; // 实际的条件

if (handlers[condition]) {
  handlers[condition]();
}

3. 多态

*   如果条件判断基于不同的对象类型,可以使用多态性,让每个对象类型实现自己的处理方法。
class Animal {
  makeSound {
    throw new Error('子类必须实现此方法');
  }
}

class Dog extends Animal {
  makeSound() {
    console.log('汪汪汪');
  }
}

class Cat extends Animal {
  makeSound() {
    console.log('喵喵喵');
  }
}

function animalSound(animal) {
 animal.makeSound();
}

const dog = new Dog();
const cat = new Cat();

animalSound(dog);
animalSound(cat);

  1. 提取函数

    • 将每个 if-else 分支中的复杂逻辑提取为独立的函数,以提高代码的可读性和可维护性。
function calculateResult(num) {
  if (num > 10) {
    return doSomethingForGreaterThan10(num);
  } else if (num < 5) {
    return doSomethingForLessThan5(num);
  } else {
    return doSomethingElse(num);
  }
}

function doSomethingForGreaterThan10(num) {
  // 处理 num > 10 的逻辑
  return num * 2;
}

function doSomethingForLessThan5(num) {
  // 处理 num < 5 的逻辑
  return num + 10;
}

function doSomethingElse(num) {
  // 处理其他情况的逻辑
  return num - 5;
}

  1. 状态模式

    • 当条件判断反映的是对象的不同状态时,可以使用状态模式来处理。
通过定义不同的状态类和一个上下文类,实现了状态的切换和处理
class State {
  handle(context) {
    throw new Error('子类必须实现此方法');
  }
}

class StateA extends State {
  handle(context) {
    // 状态 A 的处理逻辑
    console.log('处理状态 A');
    context.setState(newB());
  }
}

class StateB extends State {
  handle(context) {
    // 状态 B 的处理逻辑
    console.log('处理状态 B');
    context.setState(new StateA());
  }
}

class Context {
  constructor() {
    this.state = new StateA();
  }

 setState(state) {
    this.state = state;
  }

  request() {
    this.state.handle(this);
  }
}

// 使用示例
const context = new Context();
context.request();
context.request();

通过这些方法,可以使代码更加简洁、灵活和易于维护,减少大量 if-else 带来的复杂性和混乱