博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
重构多重循环的一个实例
阅读量:2227 次
发布时间:2019-05-09

本文共 1491 字,大约阅读时间需要 4 分钟。

重构多重循环的一个实例

黄国强 2011-12-31

一位同事提供了以下这段C#示例代码。

List<MaterialInfo> returnValue = new List<MaterialInfo>();
for (int i = 0; i < totalPoints.Count - 1; i++)
{
    CoordsDouble leftPoint = totalPoints[i];
    CoordsDouble rightPoint = totalPoints[i + 1];
    Boolean hasFound = false;
    foreach (KeyValuePair<ModelInfo2D, IList<CoordsDouble>> kvp in modelPointDictionary)
    {
        for (int j = 0; j < kvp.Value.Count - 1; j += 2)
        {
            if (kvp.Value[j] == leftPoint && kvp.Value[j + 1] == rightPoint)
            {
                returnValue.Add(kvp.Key.Material);
                hasFound = true;
                break;
            }
        }
        if (hasFound)
        {
            break;
        }
    }
    if (!hasFound)
    {
        returnValue.Add(mGrating.IncidenceMaterial);
    }
}
return returnValue;
以下是我重构后的代码示例,通过将原先循环内的代码移到新的函数中,提高了代码的可读性。
List<MaterialInfo> func1()
{
    List<MaterialInfo> returnValue = new List<MaterialInfo>();
    for (int i = 0; i < totalPoints.Count - 1; i++)
    {
        CoordsDouble leftPoint = totalPoints[i];
        CoordsDouble rightPoint = totalPoints[i + 1];
        func2(returnValue, leftPoint, rightPoint);
    }
    return returnValue;
}
void func2(returnValue, leftPoint, rightPoint))
{
    foreach (KeyValuePair<ModelInfo2D, IList<CoordsDouble>> kvp in modelPointDictionary)
    {
    if(func3(kvp,leftPoint,rightPoint))
        return ;
    }
    returnValue.Add(mGrating.IncidenceMaterial);
}

bool func3(returnValue.Add,kvp, leftPoint, rightPoint)
{
   for (int j = 0; j < kvp.Value.Count - 1; j += 2)
   {
        if (kvp.Value[j] == leftPoint && kvp.Value[j + 1] == rightPoint)
        {
            returnValue.Add(kvp.Key.Material);
            return true;
        }
   }
   return false;
}

重构是门非常重要的技术,对于不会设计的初学者,重构是个不错的起点。

转载地址:http://imefb.baihongyu.com/

你可能感兴趣的文章
国内外helm源记录
查看>>
牛客网题目1:最大数
查看>>
散落人间知识点记录one
查看>>
Leetcode C++ 随手刷 547.朋友圈
查看>>
手抄笔记:深入理解linux内核-1
查看>>
内存堆与栈
查看>>
Leetcode C++《每日一题》20200621 124.二叉树的最大路径和
查看>>
Leetcode C++《每日一题》20200622 面试题 16.18. 模式匹配
查看>>
Leetcode C++《每日一题》20200625 139. 单词拆分
查看>>
Leetcode C++《每日一题》20200626 338. 比特位计数
查看>>
Leetcode C++ 《拓扑排序-1》20200626 207.课程表
查看>>
Go语言学习Part1:包、变量和函数
查看>>
Go语言学习Part2:流程控制语句:for、if、else、switch 和 defer
查看>>
Go语言学习Part3:struct、slice和映射
查看>>
Go语言学习Part4-1:方法和接口
查看>>
Leetcode Go 《精选TOP面试题》20200628 69.x的平方根
查看>>
leetcode 130. Surrounded Regions
查看>>
【Python】详解Python多线程Selenium跨浏览器测试
查看>>
Jmeter之参数化
查看>>
Shell 和Python的区别。
查看>>