Refactoring Notes-Refactoring Methods(3)

5.Introduce Explaining Variable    If you have a complicated expression,put the result of the expression, or parts of the expression , in a temporary variable with a name that explains the purpose.   Introduce Explaining Variable is particulaly valuable with conditional logic in which it is useful to take each clause of a condition and explain what the condition means a well-named temp.   Another case is a long algorithm,in which each step in the computation can be explained with a temp.Mechanics (1)Declare a final temporary variable,and set it to the result of part of the complex expression. (2)Replace the result part of the expression with the value of the temp.Before:double price(){ return quantity*itemPrice-Math.max(0,quantity-500)*itemPrice*0.05+Math.min(quantity*itemPrice*0.1,100.0);}After:double price(){ final double basePrice= quantity*itemPrice; final double quantityDiscount=Math.max(0,quantity-500)*itemPrice*0.05 ; final double shipping=Math.min(quantity*itemPrice*0.1,100.0); return basePrice-quantityDiscount+shipping;}

Appendix: using Extract Method to complete refactoring.  The benefit of using Extract Method is that theses methodologies are available to any other part of the object that needs them.Although they are private at first,but you can relax that if another object needs them.

double price(){ return basePrice()-quantityDiscount()+shipping();}private Double basePrice(){ return quantityDiscount*itemPrice;}private Double quantityDiscount(){ return Math.min(quantity*itemPrice*0.1,100.0);}private Double shipping(){ return Math.min(quantity*itemPrice*0.1,100.0);}

6.Split Temporary Variable  If a temporary variable assigned to more than once,but is not a loop variable nor a collecting temporary variable(If the later assignments are of the form i=i+some expression, that indicates that it is a collceting temporary variable),you should use Split Temporary Method.Any variable with more than one responsibility should be replaced with a temp for each responsibility.Michanics: (1)Change the name of a temp at its declaration and its first assignment. (2)Declare the new temp as final. (3)Change all references of the temp up to its second assignment.(4) Declare the temp at its second assignment.Before:double getDistanceTravelled(int time){ double result; double acc=primaryForce/mass; int primaryTime=Math.min(time,delay); result = 0.5*acc*primaryTime*primaryTime; int secondaryTime=time-delay; if(secondaryTime>0){  double primaryVel=acc*delay;  acc=(primaryForce+secondaryForce)/mass;  result+=primaryVel*secondaryTime+0.5*acc*secondaryTime*secondaryTime; } return result;}After:double getDistanceTravelled(int time){ double result; final double primaryAcc=primaryForce/mass; int primaryTime=Math.min(time,delay); result = 0.5*primaryAcc*primaryTime*primaryTime; int secondaryTime=time-delay; if(secondaryTime>0){  double primaryVel=primaryAcc *delay;  final double secondaryAcc=(primaryForce+secondaryForce)/mass;  result+=primaryVel*secondaryTime+ 0.5*secondaryAcc*secondaryTime*secondaryTime; } return result;}

Appendix: Complete refactoringdouble getDistanceTravelled(int time){ double result; result = 0.5*getPrimaryAcc()*Math.pow(getPrimaryTime(time),2); if(getSecondaryTime(time)>0){  double primaryVel=getPrimaryAcc() *delay;  final double secondaryAcc=(primaryForce+secondaryForce)/mass;  result+=primaryVel*getSecondaryTime(time)+ 0.5*secondaryAcc*Math.pow(getSecondaryTime(time),2); } return result;}private int getPrimaryTime(int time){ return Math.min(time,delay);}private double getPrimaryAcc(){ return primaryForce/mass;}private int getSecondaryTime(int time){ return time-delay;}

7.Remove Assignments to ParametersBefore: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;}

After:int discount(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;}

8.Replace Method with Method Object  If there is a long method that uses local variables in such a way that you cannot apply Extract Method.Turn the mothod into its own object so that all the local variables became fields on that object.You can then decompose the method into other methods on the same object.Michanics: (1)Create a new class ,name it after the method. (2)Give the new class a final field for the object that hosted the original method and a field for each temporary variable and each parameter int the method. (3)Give the new class a constructor that takes the source object and each parameter. (4)Give the new class a method named “compute” and copy the body of the original method into it.

Before:class Account{int gamma(int inputVal,int quantity,int yearToDate){int importantVal1=(inputVal*quantity)+delta();int importantVal2=(inputVal*yearToDate)+100;if((yearToDate-importantVal1>100)) importantVal2-=20;int importantVal3=importantVal2*7;return importantVal3-2*importantVal1;}}

After:class Account{int gamma(int inputVal,int quantity,int yearToDate){return new Gamma(this, inputVal, quantity, yearToDate);}}

class Gamma{ public Gamma(Account account,int inputVal,int quantity,int yearToDate){  account=account;  inputVal=inputVal;  quantity=quantity;  yearToDate=yearToDate; } final Account account; int importantVal1; int importantVal2; int importantVal3; int inputVal; int quantity; int yearToDate;

 int compute(){      int importantVal1=(inputVal*quantity)+account.delta();int importantVal2=(inputVal*yearToDate)+100;if((yearToDate-importantVal1>100)) importantVal2-=20;int importantVal3=importantVal2*7;      return importantVal3-2*importantVal1; }}

9.Substitue AlgorithmReplace an algorithm with one that is clearer.

时间: 2024-12-28 13:38:49

Refactoring Notes-Refactoring Methods(3)的相关文章

Ceylon 1.1 进度报告,基于 JVM 的编程语言

Ceylon 1.1 已经开发6个月了,是时候给大家交待一下开发的进度了.这在 6 个月内我们处理并关闭了超过 650 个 issue,关于编译器和语言模块方面,其中 IDE 方面的问题有 300 个. 目前 Ceylon 1.1 优先级最高的是: 语言模块 API 的最终确认 清理和最小化使用 Java 和 JavaScript 代码 处理影响 Java 互操作的遗留问题 性能提升 IDE 构建的性能 当然,也包括很多 bug 修复. 语言方面的变化 语言方面的变化比较少,基本上 1.0 后我

.net辅助工具列表

最近对.net的辅助工具比较感兴趣,网上也已经有.net的十个必备工具的帖子了,这里提供了一份全面的工具列表:Code generation NVelocity CodeSmith X-Code .NET XGoF - NMatrix / DEVerestCompilation eXtensible C# - ResolveCorp Mono DotGNU - GNUObfuscation LSW-IL-Obfuscator - Lesser Software Demeanor for .NET

.NET Test Driven Development

development Test Driven DevelopmentBooks Lessons Learned in Software Testing by Cem Kaner, James Bach, and Bret Pettichord.Pragmatic Unit Testing in C# by the Pragmatic Programmers Andy Hunt and Dave Thomas, the preview chapters (one, two) look good.

iOS 中正则表达式使用方法汇总

iOS 中正则表达式使用方法汇总 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 某种语言中的正则工具算是木桶,而这个工具处理的是正则表达式,算是水,那么水很多,无论是淡水还是咸水,或是雨水,至

Python属性和方法

关键字:Python 属性 方法原文:http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html    Shalabh Chaturvedi Copyright 2005-2009 Shalabh Chaturvedi All Rights Reserved. About This Book Explains the mechanics of object attri

程序员们,那些年吹过的牛逼都实现了吗?

有一部分程序员中的老司机,他们善于找各种借口,少干活,少背锅,多拿钱.但是,更多的程序员坦诚.直白.意气用事. 那些年吹过的牛逼都实现了吗?还是随风而去? 这个功能简单,一天就能搞完 程序员拿到一个新功能,心里暗暗发笑,这剧情我见过啊.于是脱口而出,这功能简单,一天就能做完,明天上线肯定没问题. 结果,眼看着到自己设定的截止日期了,还有一部分代码没有写完,怎么办? 很简单啊,又不是生死状,又不要命.解决办法很简单,加班--- 程序员,那些年吹过的牛逼,最后都自己加班了. 这段代码肯定没bug,我

UVa 10879 Code Refactoring:因数分解

10879 - Code Refactoring Time limit: 3.000 seconds http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=100&page=show_problem&problem=1820 "Harry, my dream is a code waiting to be broken. Break the code, solve

[重构 Swift 中单例的用法](Refactoring singleton usage in Swift)

本文讲的是[重构 Swift 中单例的用法](Refactoring singleton usage in Swift), 使代码库更加简洁.模块化.和可测试的技巧 2017 年 2 月 10 日 在软件开发中,单例模式有足够的原因被广泛的不推荐和不赞成.它们难以测试或者说是不可能测试,当它们在其他类中隐式调用时会使你的代码库混乱,让代码难以复用.大部分时候,一个单例其实就相当于一个伪全局变量.每个人都知道,至少知道这是一个糟糕的主意.然而,单例有时又是不可避免且必须的.我们如何能把它们用一种整

VS2015上又一必备免费插件:Refactoring Essentials

原文:VS2015上又一必备免费插件:Refactoring Essentials (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:Refactoring Essentials是一款用于代码分析和重构的开源免费VS2015插件,其功能丰富强大,必然会成为类似Web Essentials这样的必备插件. 之前由SharpDevelop团队开发且用于SharpDevelop这个开源IDE中的重构插件"NR6Pack"改名为&