首页 > 代码库 > 重构指南 - 分解复杂判断(Remove Arrowhead Antipattern)

重构指南 - 分解复杂判断(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);    }}

 

重构后的代码,大大提高了可读性和以后的可维护性。

 

重构指南 - 分解复杂判断(Remove Arrowhead Antipattern)