避免过度使用if语句

150 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 6 天,点击查看活动详情

我在开发过程中,遇到判断,总是下意识的去使用if语句,等回头再去改代码的时候会发现,用了太多的if,一层包一层,一个后面还有一个,虽然if用起来是方便,但是也不能过度使用,通过查找资料,找到以下方式避免过度使用if,大家一起探讨下,换一种思维解决问题。

1、三元条件运算符

示例1

使用if的代码

function personInfo(person) {
  if (!person.name) {
    return error('name is require')
  } else if (!person.age) {
    return error('age is required')
  } else if (!person.job) {
    return error('job is required')
  } else {
    return person
  }
}

重构的代码

const personInfo = person =>
  !person.name   ? error('name is required')
  : !person.age ? error('age is required')
  : !person.job  ? error('job is required')
                    : person

示例2

使用if的代码

function getEventTarget(evt) {
    if (!evt) {
        evt = window.event;
    }
    if (!evt) {
        return;
    }
    const target;
    if (evt.target) {
        target = evt.target;
    } else {
        target = evt.srcElement;
    }
    return target;
}

重构的代码

function getEventTarget(evt) {
  evt = evt || window.event;
  return evt && (evt.target || evt.srcElement);
}

2、短路逻辑运算符

示例1

使用if的代码

const isOnline = true;
const personInfo= ()=>{};
const person = {
    name:'Join',
    age:18,
    job:'程序媛'
};

if (isOnline){
    personInfo(person);
}

重构的代码

const isOnline = true;
const personInfo= ()=>{};
const person = {
    name:'Join',
    age:18,
    job:'程序媛'
};

isOnline&&personInfo(user);

示例2

使用if的代码

const active = true;
const person = {
    name:'Join',
    age:18,
    job:'程序媛'
};
const changeAge = ()=>{};
if (active&&person){
    changeAge();
}

重构的代码

const active = true;
const person = {
    name:'Join',
    age:18,
    job:'程序媛'
};
const changeAge = ()=>{};
active && person && changeAge();

3、非分支策略

使用switch的代码

switch(color){
    case 'green':
      return 'The color is green';
      break;  
    case 'blue':
      return 'The color is blue';
      break;  
	case 'yellow':
      return 'The color is yellow';
      break;  
    default:
      return 'Default'
}

重构的代码

const getColor = (color) =>({
  "green": "The color is green",
  "blue": "The color is blue",
  "yellow": "The color is yellow",  
})[color]||'Default';

getColor("green")

4、功能委托

使用if的代码

function itemDropped(item, location) {
    if (!item) {
        return false;
    } else if (outOfBounds(location) {
        var error = outOfBounds;
        server.notify(item, error);
        items.resetAll();
        return false;
    } else {
        animateCanvas();
        server.notify(item, location);
        return true;
    }
}

重构的代码

function itemDropped(item, location) {
    const dropOut = function() {
        server.notify(item, outOfBounds);
        items.resetAll();
        return false;
    }
    const dropIn = function() {
        server.notify(item, location);
        animateCanvas();
        return true;
    }
    return !!item && (outOfBounds(location) ? dropOut() : dropIn());
}

5、作为数据的函数

使用if的代码

const calc = {
    run: function(op, n1, n2) {
        const result;
        if (op == "add") {
            result = n1 + n2;
        } else if (op == "sub" ) {
            result = n1 - n2;
        } else if (op == "mult" ) {
            result = n1 * n2;
        } else if (op == "div" ) {
            result = n1 / n2;
        }
        return result;
    }
}
calc.run("sub", 5, 3); //2

重构的代码

const calc = {
    add : function(a,b) {
        return a + b;
    },
    sub : function(a,b) {
        return a - b;
    },
    mult : function(a,b) {
        return a * b;
    },
    div : function(a,b) {
        return a / b;
    },
    run: function(fn, a, b) {
        return fn && fn(a,b);
    }
}
calc.run(calc.mult, 7, 4); //28

6、多态性

使用if的代码

const bob = {
  name:'Bob',
  salary:1000,
  job_type:'DEVELOPER'
};
const mary = {
  name:'Mary',
  salary:1000,
  job_type:'QA'
};
const calc = (person) =>{
    if (people.job_type==='DEVELOPER')
        return person.salary+9000*0.10;

    if (people.job_type==='QA')
        return person.salary+1000*0.60;
}
console.log('Salary',calc(bob));
console.log('Salary',calc(mary));

重构的代码

const qaSalary  = (base) => base+9000*0.10;
const devSalary = (base) => base+1000*0.60;
//Add function to the object.
const bob = {
  name:'Bob',
  salary:1000,
  job_type:'DEVELOPER',
  calc: devSalary
};
const mary = {
  name:'Mary',
  salary:1000,
  job_type:'QA',
  calc: qaSalary
};
console.log('Salary',bob.calc(bob.salary));
console.log('Salary',mary.calc(mary.salary));

上述6点就是我查到的重构方法,有其他的方式后续继续补充。