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

 时间:2026-02-14 05:42:41

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

  • 代码怎么写才看起来是有经验的程序员
  • 怎么找有经验的程序员?
  • 程序员开发文档怎么写
  • 如何成为合格的程序员
  • 程序员接外包项目需要注意哪些细节
  • 热门搜索
    什么是现货投资 白醋洗头有什么好处 normal是什么意思 感人肺腑的意思 nmsl什么意思 倾轧什么意思 什么是dlp 隔岸观火的意思 高程是什么意思 天然气12t什么意思