多语言展示
当前在线:1203今日阅读:2今日分享:38

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

有经验的程序员,他们写出的代码带着返璞归真的简约感,上期分享了几个小例子,大家感受颇深,这期继续分享。
方法/步骤
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

注意事项
1

代码之路任重而道远,需要不断吸取经验

2

帮助到你请点赞,更多疑问可以留言

推荐信息