马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

重构之移除对参数的赋值(Remove Assignments to Parameters)

  [复制链接]
查看2787 | 回复5 | 2019-2-28 23:15:23 | 显示全部楼层 |阅读模式
在开始写之前,我想了很久,实在想不出很好的解释去讲解这一重构手法的所以然来;所以我们就直接从代码上入手吧。重构前
[C#] 纯文本查看 复制代码
 public int discount(int inputVal,int quantity,int yearToDate)
        {
            if (inputVal>50)
            {
                inputVal -= 2;
            }
            if (quantity>100)
            {
                inputVal -= 1;
            }
            if (yearToDate>10000)
            {
                inputVal -= 4;
            }
            return inputVal;
        }

重构后
[C#] 纯文本查看 复制代码
 
public int discount1(int inputVal, int quantity, int yearToDate)
        {
            int result = inputVal;
            if (inputVal > 50)
            {
                result -= 2;
            }
            if (quantity > 100)
            {
                result -= 1;
            }
            if (yearToDate > 10000)
            {
                result -= 4;
            }
            return result;
        }

从上面的代码段看,相信大家都会有一些疑问,这样重构有何意义呢?不就增加了个临时变量和更改了赋值吗?不增加不改变不还是一样。。。。。
这正是为什么在写之前想了很久,因为大家的这些疑问我也存在过;但大家有没有想过如果传入的参数是一个对象呢?而函数又带有了复杂逻辑,这样就很可能把人弄迷糊了,所以当你函数里存在对参数进行了赋值你大可先考虑下是否要用“ 重构之移除对参数的赋值(Remove Assignments to Parameters)”这一手法先进行一次重构,然后在去使用其实的重构手法把函数重构的漂漂亮亮的。


参考文献
重构——改善既有代码的设计   【美】Martin Fowler 著
                                                                         熊节 译






ibcadmin | 2019-3-4 14:25:42 | 显示全部楼层
[C#] 纯文本查看 复制代码
public int discount1(int inputVal, int quantity, int yearToDate)
        {
            
            if (inputVal > 50)
            {
               return  result - 2;
            }
            if (quantity > 100)
            {
                return  result - 1;
            }
            if (yearToDate > 10000)
            {
               return  result - 4;
            }
            return 0;
        }


我觉得直接return比较好

C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
剑弑 | 2019-3-4 21:51:14 | 显示全部楼层
ibcadmin 发表于 2019-3-4 14:25
[mw_shl_code=csharp,true]public int discount1(int inputVal, int quantity, int yearToDate)
        { ...

嗯嗯,后面会有讨论到直接return会减少运行行数。
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则