當代碼中有多層嵌套時,會降低代碼的可讀性,對於以後的修改也增加難度,所以我們需要分解複雜的判斷並儘快返回。 重構前代碼 重構後代碼 重構後的代碼,大大提高了可讀性和以後的可維護性。 ...
當代碼中有多層嵌套時,會降低代碼的可讀性,對於以後的修改也增加難度,所以我們需要分解複雜的判斷並儘快返回。
重構前代碼
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); } }
重構後的代碼,大大提高了可讀性和以後的可維護性。