重构之前的代码
private static void OldMethod(BusinessObjectInfo parentBOInfo){ IList bosPropertyInfo = parentBOInfo.BOsPropertyInfos; if ((bosPropertyInfo.Count == 1) && (null != parentBOInfo.TreeChildPropertyInfo)) { //action one } else if (((bosPropertyInfo.Count > 1) && (null != parentBOInfo.TreeChildPropertyInfo)) || ((bosPropertyInfo.Count > 0) && (null == parentBOInfo.TreeChildPropertyInfo))) { //action two }}
初步重构
private static void NewMethod(BusinessObjectInfo parentBOInfo){ IList childrenProperties = parentBOInfo.BOsPropertyInfos; var childrenPropertiesCount = childrenProperties.Count; if (childrenPropertiesCount <= 0) { return; } var hasTreeChild = null != parentBOInfo.TreeChildPropertyInfo; if (hasTreeChild) { if (childrenPropertiesCount == 1) { //action one } } else { //action two }}
最终版本 if判断时简洁处理只使用必要的参数 合并if到同一级别 所以就得如下:
private static void NewMethod2(BusinessObjectInfo parentBOInfo){ IList childrenProperties = parentBOInfo.BOsPropertyInfos; var childrenPropertiesCount = childrenProperties.Count; if (childrenPropertiesCount <= 0) { return; } var hasTreeChild = null != parentBOInfo.TreeChildPropertyInfo; if (hasTreeChild && childrenPropertiesCount == 1) { //action one } else { //action two }}
两个数比较大小:if..else重构if
本文探讨了如何通过重构代码来提升其可读性和维护性。通过对原始代码进行逐步简化和优化,展示了如何减少复杂的if条件判断,使代码更加清晰易懂。最终版本的代码仅使用必要的参数,将if条件合并至同一级别,显著提高了代码质量。

被折叠的 条评论
为什么被折叠?



