重构:一个简单的IF语句

时间:2022-04-24
本文章向大家介绍重构:一个简单的IF语句,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
private static void OldMethod(BusinessObjectInfo parentBOInfo)
{
    IList<BusinessObjectsPropertyInfo> 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<BusinessObjectsPropertyInfo> 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
    }
}

    以上两种写法并不完全等价(你能找出来吗?),不过就当时的业务逻辑来说,这样写是没错的。

   上面的写法,还是错了,应该是这样:

private static void NewMethod2(BusinessObjectInfo parentBOInfo)
{
    IList<BusinessObjectsPropertyInfo> 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
    }
}