重构指南 - 分解复杂判断(Remove Arrowhead Antipattern)
当代码中有多层嵌套时,会降低代码的可读性,对于以后的修改也增加难度,所以我们需要分解复杂的判断并尽快返回。
重构前代码
public class Security { public ISecurityChecker SecurityChecker { get; set; } public Security(ISecurityChecker securityChecker) { SecurityChecker = securityChecker; } public bool HasAccess(User user, Permission permission, IEnumerable<Permission> exemptions) { bool hasPermission = false; if (user != null) { if (permission != null) { if (exemptions.Count() == 0) { if (SecurityChecker.CheckPermission(user, permission) || exemptions.Contains(permission)) { hasPermission = true; } } } } return hasPermission; } }
重构后代码
public class Security { public ISecurityChecker SecurityChecker { get; set; } public Security(ISecurityChecker securityChecker) { SecurityChecker = securityChecker; } public bool HasAccess(User user, Permission permission, IEnumerable<Permission> exemptions) { if (user == null || permission == null) return false; if (exemptions.Contains(permission)) return true; return SecurityChecker.CheckPermission(user, permission); } }
重构后的代码,大大提高了可读性和以后的可维护性。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步