代码的坏味道——滥用控制语句

         前言:避免滥用控制语句,应该尽量简化代码逻辑,避免出现重复和冗余代码。通过合理的模块化和抽象来简化代码结构。

一、嵌套的代码

不管是if、for、switch、回调等,都应该避免出现多级嵌套

badCase:

        function fn1(a) {
            setTimeout(() => {
                console.log(a);
                a--;
                setTimeout(() => {
                    console.log(a);
                    a--
                    setTimeout(() => {
                        console.log(a);
                        a--
                        setTimeout(() => {
                            console.log(a);
                            a--
                            setTimeout(() => {
                                console.log(a);
                            }, 1000);
                        }, 1000);
                    }, 1000);
                }, 1000);
            }, 1000);
        }
        fn1(5)

goodCase:

    function fn1(a) {
          new Promise((res,rej)=>{
                res(a)
            })
            .then((params)=>{
              return  new Promise((res,rej)=>{
                setTimeout(() => {  console.log(params);res(--params) }, 1000) }) 
             })
             .then((params)=>{
              return  new Promise((res,rej)=>{
                setTimeout(() => {  console.log(params);res(--params) }, 1000) }) 
             })
             .then((params)=>{
              return  new Promise((res,rej)=>{
                setTimeout(() => {  console.log(params);res(--params) }, 1000) }) 
             })
             .then((params)=>{
              return  new Promise((res,rej)=>{
                setTimeout(() => {  console.log(params);res(--params) }, 1000) }) 
             })
             .then((params)=>{
              return  new Promise((res,rej)=>{
                setTimeout(() => {  console.log(params);res(--params) }, 1000) }) 
             })        
         }
         let a=5
         fn1(a)

二、if和else(避免使用else)

else会增加块级区域,虽然一时影响不大,但未必后续添加嵌套逻辑。可以使用卫语句取代。

badCase:

if (a > b) {
  console.log('a')
} else {
  console.log('b')
}

goodCase:

if (a > b) {
  console.log('a')
  return ;
}
console.log('b')

三、重复的switch

过多的switch会出现大量重复的结构,可以采用对象映射、函数映射、策略模式等。

badCase:

function handleAction(type, data) {  
    switch (type) {  
        case 'add':  
            return addData(data);  
        case 'delete':  
            return deleteData(data);  
        case 'update':  
            return updateData(data);  
        // ... 假设这里还有更多的case  
        default:  
            throw new Error('Unknown action type');  
    }  
}  

// 使用  
handleAction('add', { id: 1, value: 'Hello' });

goodCase:

const actionHandlers = {  
    'add': addData,  
    'delete': deleteData,  
    'update': updateData,  
    // ... 可以轻松添加更多类型  
};  
  
function handleAction(type, data) {  
    const handler = actionHandlers[type];  
    if (handler) {  
        return handler(data);  
    }  
    throw new Error('Unknown action type');  
}  
  
  
// 使用  
handleAction('add', { id: 1, value: 'Hello' });

四、使用es6代替for语句

很多场景都需要循环去加工或处理一些数据,使用循环是必不可免的,使用es6可以减少结构的嵌套,并且支持链式调用。

badCase:

let people = [  
    { name: 'Alice', age: 25 },  
    { name: 'Bob', age: 17 },  
    { name: 'Charlie', age: 22 },  
    { name: 'David', age: 15 }  
];  
  
let adults = [];  
  
for (let i = 0; i < people.length; i++) {  
    if (people[i].age > 18) {  
        adults.push(people[i]);  
    }  
}  
  
console.log(adults);

goodCase:

let people = [  
    { name: 'Alice', age: 25 },  
    { name: 'Bob', age: 17 },  
    { name: 'Charlie', age: 22 },  
    { name: 'David', age: 15 }  
];  
  
let adults = people.filter(person => person.age > 18);  
  
console.log(adults);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值