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;第一种代码是受到早期的某些思想:使用一个变量来存储返回结果。 事实上当你知道结果第一时间就应返回。
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!
9.参数过多,超过3个反例:public void RegisterUser(string userName, string password, string email, string phone){ }优化后:public void RegisterUser(User user){ }过多的参数让读者抓不住代码的意图,过多的参数会影响运行的稳定性。当参数过多你首先应该考虑把它们聚合为一个Model
代码之路任重而道远,需要不断吸取经验
帮助到你请点赞,更多疑问可以留言