代码怎么写才看起来是有经验的程序员-二

2025-10-31 07:27:35

1、7.嵌套判断

反例:

var isValid = false;

if (!string.IsNullOrEmpty(user.UserName))

{

    if (!string.IsNullOrEmpty(user.Password))

    {

        if (!string.IsNullOrEmpty(user.Email))

        {

            isValid = true;

        }

    }

}

return isValid;

优化后:

if (string.IsNullOrEmpty(user.UserName)) return false;

if (string.IsNullOrEmpty(user.Password)) return false;

if (string.IsNullOrEmpty(user.Email)) return false;

 return true;

第一种代码是受到早期的某些思想:使用一个变量来存储返回结果。 事实上当你知道结果第一时间就应返回。

2、8.使用前置条件

反例:

if (!string.IsNullOrEmpty(userName))

{

    if (!string.IsNullOrEmpty(password))

    {

        //register

    }

    else

    {

        throw new ArgumentException("user password can not be empty");

    }

}

else

{

    throw new ArgumentException("user name can not be empty");

}

优化后:

if (string.IsNullOrEmpty(userName)) throw new ArgumentException("user name can not be empty");

if (string.IsNullOrEmpty(password)) throw new ArgumentException("user password can not be empty");

//register

优化后的更符合编程的顺序,首先要满足前置条件,否则wrong!

3、9.参数过多,超过3个

反例:

public void RegisterUser(string userName, string password, string email, string phone)

{

}

优化后:

public void RegisterUser(User user)

{

}

过多的参数让读者抓不住代码的意图,过多的参数会影响运行的稳定性。当参数过多你首先应该考虑把它们聚合为一个Model

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢