前端TS代码优化:多if else分支拆分为独立函数方案咨询
代码拆分方案
推荐优先按dataIndex维度拆分函数,该维度下每个函数对应单个字段的全量处理逻辑,业务内聚性更强。拆分后代码如下:
// 处理ReportEffectiveDate字段变更逻辑 function handleReportEffectiveDateChange(record: LoadModel) { if (record.EffectiveDate > record.ReportEffectiveDate) { record.EffectiveDate = null; tableStore.update(record); Modal.error({ content: translate('ReportEffectiveDatecantbelessthanoldeffectivedate'), }); console.log('error'); } else if (record.EffectiveDate == record.ReportEffectiveDate) { record.ReportEffectiveDate = null; tableStore.update(record); } } // 处理EffectiveDate字段变更逻辑 function handleEffectiveDateChange(record: LoadModel, status: RowStatus, oldValue: any, newValue: any) { if (status === 'added') { const isValid: boolean = checkIsEffectiveDateValid(record); if (!isValid) { record.EffectiveDate = null; tableStore.update(record); } } else if (status === 'edited') { const maxEffectiveDateRecord: LoadModel = getMaxEffectiveDateRecord(record); if (record.EffectiveDate > maxEffectiveDateRecord.EffectiveDate) { if (newValue < maxEffectiveDateRecord.EffectiveDate) { record.EffectiveDate = oldValue; tableStore.update(record); } } } } // 改造后的主入口函数 function handleTableRowChange(record: LoadModel, oldValue: any, newValue: any, dataIndex: string) { console.log(record, oldValue, newValue, dataIndex); if (!newValue) return; const status: RowStatus = tableStore.getRowStatus(record); switch(dataIndex) { case 'ReportEffectiveDate': handleReportEffectiveDateChange(record); break; case 'EffectiveDate': handleEffectiveDateChange(record, status, oldValue, newValue); break; default: // 后续新增字段处理逻辑可直接扩展case break; } }
两种拆分方案对比
按dataIndex拆分明显优于按status拆分,核心原因如下:
- 业务内聚度更高:同一个字段的校验、错误提示、数据更新逻辑全部收敛在同一个函数中,后续需要调整该字段规则时,不需要跨多个函数修改代码
- 扩展成本更低:如果后续新增其他字段的处理逻辑,只需要新增对应字段的处理函数,在主入口加case即可,符合开闭原则
- 排查问题更高效:如果线上出现
ReportEffectiveDate相关的bug,直接定位到对应处理函数即可,不需要去多个status分支里筛选相关逻辑
多分支 vs 独立函数方案优劣
独立函数方案远优于堆在同一个函数里写多if else分支,优势体现在:
- 可复用性:抽离的字段处理函数可以在其他业务场景直接调用,不需要重复写校验逻辑
- 可测试性:每个小函数只依赖明确的入参,可以单独写单元测试覆盖所有分支,不需要构造全量的主函数入参
- 可维护性:单个函数代码量控制在20行以内,逻辑清晰,修改单个字段的逻辑不会影响其他分支的代码,降低改出bug的概率
内容的提问来源于stack exchange,提问作者Negin
相关产品推荐
相关产品推荐

