如何优化多服务场景下的if判断语句?
重构多if判断的最佳实践
针对你这种根据不同授权标识调用对应服务校验用户的场景,最简洁且易维护的方案是使用**映射表(对象)**替代冗余的if判断,核心思路是将授权标识与对应的用户校验逻辑一一绑定,通过键值对直接匹配处理逻辑。
具体实现步骤
1. 构建授权标识与校验逻辑的映射表
将每个授权标识对应的用户获取逻辑封装为函数,统一存入一个对象中。这种方式可以兼容不同服务的方法调用(如currUser())或属性访问(如currentUserValue):
// 定义授权标识到用户校验逻辑的映射 const authUserValidators = { text1: () => this.text1Service.currUser(), text2: () => this.text2Service.currentUserValue, text3: () => this.text3Service.currUserValue };
2. 统一处理用户校验逻辑
根据传入的authorization值,从映射表中获取对应的校验函数,执行后判断是否存在有效用户:
// 获取当前授权对应的校验函数 const validator = authUserValidators[authorization]; if (validator) { const currUser = validator(); // 存在有效用户则返回true,否则返回false(或根据业务逻辑继续执行) return !!currUser; } // 无匹配授权标识时的默认返回 return false;
扩展优化建议
统一服务接口(可选):如果后续有新增服务的需求,尽量统一各服务的用户获取方式(比如都改为
currUser()方法),这样映射表可以简化为直接存储服务实例,进一步减少冗余:// 假设所有服务统一为currUser()方法 const authServices = { text1: this.text1Service, text2: this.text2Service, text3: this.text3Service }; const service = authServices[authorization]; return service ? !!service.currUser() : false;类型安全(TypeScript场景):通过枚举定义授权标识,避免拼写错误,增强代码健壮性:
enum AuthType { Text1 = 'text1', Text2 = 'text2', Text3 = 'text3' } const authUserValidators: Record<AuthType, () => any> = { [AuthType.Text1]: () => this.text1Service.currUser(), [AuthType.Text2]: () => this.text2Service.currentUserValue, [AuthType.Text3]: () => this.text3Service.currUserValue }; // 使用时做类型断言 const validator = authUserValidators[authorization as AuthType];
方案优势
- 消除冗余的if判断,代码结构更简洁清晰
- 新增授权类型时,仅需在映射表中添加条目,无需修改核心校验逻辑,符合开闭原则
- 所有校验逻辑集中管理,便于后续维护和修改
内容的提问来源于stack exchange,提问作者diegosmon
相关产品推荐
相关产品推荐

