Class Note for CMPSCI 220 at UMass(26)
Class Note for CMPSCI 220 at UMass(26)
Popular in Course
Popular in Department
This 7 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at University of Massachusetts taught by a professor in Fall. Since its upload, it has received 17 views.
Reviews for Class Note for CMPSCI 220 at UMass(26)
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 02/06/15
Refactoring Extract Method CMPSCI 220 291A I Refactoring for extracting a code fragment Programming Methodology into a method Fall 2008 I Goals I Enable reuse I Avoid cuteandepaste programming 16 Refactoring I Make longer methods shorter and more with thanks to Frank Tip readable UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Extract Method How Extract Method How I Create a new method invent a name for it I Scan extracted code for variables local in I Pick a name describing what the method does scope to source method I Only used in target method declare in target I Co extracted code from source method to Py method new target method I I Used in source method and read but not assigned in target method pass in as parameters I Used in source method and assigned in target method and new value used in source method pass in as parameters and return changed value I At most one variable can be modi ed UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Example Extract Method Example Extract Method 2 1 139 Void printowing void printowing Enumeration e or der selements Enumeration e or der selements double outstanding 00 double outstanding 00 printBanner O calculate outstanding I I E ntln E while ehaSMor eElementS ntln u Order each 0rder enextElement L ntln I outstanding eachgetAmount calculate outstanding 3 while ehaSMor eElementS l ilS Order each 0rder enextElement intln name A i outstanding eachgetAmount L i i print detaus public void printBanner O Systemoutpr intln name name SyStemOUtPr intlm Systemoutpr intln amount outstanding SyStemOUtPr intlm Stomer OWES i H System utprin m ttttttttttttttttttttttttt UWEREITY 0E MASSACiiusElTS AMHERST Department of Computer Science Example Extract Method 3 Example Extract Method 4 1 void print0wing vqjdmquotjntuMim 1 Enumeration e orderselements I orderselem double outstanding 00 I l li Jj E printBanner printBanner outstanding get0utstandinge outstanding 39TuEEarTc g quot quot quotquotquotquot printDetailsoutstanding IsMoreElementsC Ich 0rdereI Iing eachge39 public double get0utstandingEnumeration e double outstanding L while ehasMoreElements printDetailsoutstanding Order each 0rderenextElement outstanding eachgetAmount public void printDetailsdouble outstanding Systemoutprintln name name return outstanding Systemoutprintln amount outstanding H public void printDetailsdouble outstanding public void printBanner public void printBanner r UNIVERSITY OF MASSACHLlSETTS AMHERST Department oanmputer Science 7 UNIVERSITY OF MASSACHUSETTS AMHERST Department ofCompmoer Science Example Extract Method 5 Example Extract Method 6 void print0wing void print0wing printBanner printBanner double outstanding get0utstanding double outstanding get0utstanding printDetailsoutstanding printDetailsoutstanding public double get0utstanding public double get0utstanding Enumeration e orderselements Enumeration e orderselements double 777 H quot F 00 double result 00 while ehasMoreElements while ehasMoreElements forgeriegichi 0rderenextElement Order each 0rderenextElement H eachgetAmount result eachgetAmount return 77777777 77 return result public void printDetailsdouble outstanding public void printDetailsdouble outstanding public void printBanner public void printBanner UNIVERSITY or MAssAcHusE I rs AMHERST Department of Computer Science UNIVERSITY or MAssAcHusFrTs AMHERST Department of Computer Science Variant Computed Previous Value Variant Refactored 4 1 void print0wingdouble previousAmount void printowingdouble previousAmount EnIImerationeord rsLeemenEs double outstanding previousAmount 12 I nding printBanner quotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquotquot quot outstanding get0utstandingoutstanding printBanner printDetailsoutstanding calculate outstanding While emasMoreElementsox public double get0utstandingdouble initialValue Order each 0rderenextElementi Enumeratwn e forders39 emquottso outstanding eachgetAmount 61091019 result 1mthva while ehasMoreElements printDetauswutstanding Order each 0rderenextElement result eachgetAmount public void printDetailsdouble outstanding public void printBanner I EtUI quot FESUIt public void printDetailsdouble outstanding public void printBanner UNIVERSITY MAsgAEImssns AMHERST Department of Computer ecience Umvsnsmfor MAsgAchsnTs AMHERST Department of Computer Science Extract Method Considerations Problem Case void rintOwin I If the extracted code changes multiple local EnEmemtmnge Emergeiementso variables double outstanding 00 int count 0 I Pick different code to extract printBanner O I Aim for multiple methods each With one return value calculate outstanding while ehasMoreElements I Try applying Replace Temp With Query gmergach igndgngh I In essence recomputing the value each time E I Not always directly possible printDetailsoutstanding count I Performance issues ublic void rintDetails double outstandin I Or use Replace Method With Method Oblect p p int count g I Heavy weight W turns method into its own object Wm vmd pmntBannero 39 39 39 UNIVERSITY or MASSACHLlSETES AMHERST Department of Computer Science UNIVERSITY or MAssAcHusEnsi AMHERST Department of Computer Science Inverse of Extract Method Refactoring Inline Method Replace Temp with Query I Replace method call with body of called method I Goal E ate temporary variable used to I Commonly applied by optimizing compilers hold result of an expression I When to apply I How I As an intermediate step when a group of methods is b adly facto red I If too much delegation makes code hard to follow I Declare temp as Final and recompile I Compiler will alert you if multiple assignments exist I Various complicating issues I Extract the expression into a method I Polymorphic 5211 sites I Replace all references to the temp With calls to that method I Recursion E I Multi1e return I Oints H UNIVERSITY OF MASSACHUSETTS AMHERST Department Of Computer Science UNIVERSITY OF MASSACHUSHTS AMHERST Department Of Compmer Science Refactoring Example Replace Temp with Query Replace Temp with Query double getPr iceO i I Complicating ISSUES t baSEPNCE L double discountFactor 39 39 if basePr ice gt 1000 discountFactor 095 I Expression may have side effects else dwmuntmctw MS return basePr ice discountFactor I Try applying Separate Query from Modi er I Expression may have a different value at places Where the temp is used I Temps that are assigned more than once in loop 5 7 I Performance issues UmvsnsmioE MASSACHUSHTS AMHERsr Department of Computer Science Example Example Replace Temp with Query 2 Replace Temp with Query 3 douIbleqetPrice I IIgt 1000 discourPcT ctor 095 else discountFactor 098 return I discountFactor public int basePriceO public int basePriceO return quantity itemPrice return quantity itemPrice UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science E I I 7 UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Example Example Replace Temp with Query 4 Replace Temp with Query 5 double getPriceO double getPriceO return basePriceO discouIItFactorO return basePriceO discountFactorO public Jaimie disEEIIn39t39FaEfo39rT39quot39 public double discountFactorO I double discountFactor i return basePriceO gt 1000 7 095 098 if basePriceO gt 1mm discountFactor 095 else I public int basePriceO discountFactor 098 return quantity itemPrice I return discountFactor I I public int basePriceO return quantity itemPrice UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Refactoring Replace Method with Replace Method with Method Method Object Object How I Create new class named after method containing I Fl nal field for object that hosted original method I Long method that uses local variables in a way that precludes using Extract Method I I I I Field for each temp Variable and parameter in method I Tum the methOd Into Its own ObleCt so that I Constructor taking source object and each parameter I Local Variables become fields and initializing corresponding fields I Method can then be decomposed into other I New method called comp uteO with same return methods on the same object type as original method I Copy body of original method into computeO I Use source object field for any invocations of methods in original object UNlVERSITY 0E MASSAcuuSETIS AMHERST Department of Computer Science 7 7 iUlhviEksilTY 0E MASSACHUSHTS AMHERST Department of Computer Science Example Replace Method with Example Replace Method with Method Object Method Object 2 public class Account class Gamma int a m J nt fnputVa lTinE auantTtST int private final AccouiIt account 39 int importantValuel 39 private int inputa inputVal quantity delta i private int quantity int importantValueZ private int year ToDate inputVal year ToDate 100 PrWate Wt 1mP0r tantV01U91 I I I l l l l l iF yearToDate e importantValuel gt 100 private int importantValuez importantValueZ 20 private int importantValues int impor tt pr tantValueZ r etur n impc Z importantVa UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science I 7 UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Example Replace Method with Example Replace Method with Method Object 3 Method Object 4 class Gamma public class Account public GammaAccount source int inputValAr g int gammaint inputVal int quantity int year ToDate Wt quantltyAr QI YEOY TODatEAr Q return new Gammathis inputVal quantity account sour ce year ToDatecompute inputVal inputValAr g quantity quantityAr g year ToDate year ToDateAr g class Gamma public int computeO public GammaAccount sour ce int inputValAr g private final Account account int quantityAr g year ToDateAr g PUVate int WU01 public int computeo private int quantity importantValuel private int year ToDate inputVal quantity accountdelta Private int importantValueh importantValueZ inputVal year ToDate 100 private int importantValueZ it year ToDate e impor tantValuel gt 100 private int importantValueS importantValueZ 7 20 importantValueS importantValueZ 7 return importantValue3 e Z importantValuel UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Refactoring Move Method Move Method How I Method is using or is used by more features I Examine features used by source method that of another class than of its defining class are defined on source class I Create a new method with s n ar body in the I Consider Whether they should also be moved class it uses or is used by most I Check for overriding definitions in subclasses I Turn the old method into a simple delegation or superclasses I Or remove it altogether I In general cannot move if there is polymorphism UNlVERSITY 0F MASSAcuuSETTS AMHERST Department of Computer Science 7 iquERSITY 0F MASSAcHuSErTS AMHERST Department of Computer Science Move Method How Example Move Method public class Account I Declare method 111 the target class 39 double ovePdPQFtChargeo 39 1F typeisPremium double result 10 if daysoverdrawn gt 7 result daysoverdrawn e 7 return result else return daysOverdrawn 175 l Copy code from source method I Adjust references to source I Determine how to access target object from aou b le39b39ankt ar39g39etj T quot SOLIICC double result 45 if daysoverdrawn gt 0 I Turn source method mto delegatmg method result overdraFtChargeO I I return result I Removal 1s opt1onal private AccountType type private int daysOverdrawn UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Example Move Method Example Move Method 2 class AccountType I Observauons boolean isPremiumO I Reference to eld daysOverdrawn in source double ovenzy gftghiqrgeOIIt daysOverdrawn class assume th1s eld needs to stay 1n source if Q doubl I Source class already has po1nter to target class if F result T 777777777 7 7 085 I OptIons for makmg a feature avallable to moved return result 9 Se obect m 1ts new pos1t10n returnf 777777777 quot 175 l I Move 1t to target class as well ii I CfCZtC Of Use 2 reference tO SOUfCC Class I Pass the Whole source object as parameter 7 I If the feature is a eld pass it as a parameter UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Example Move Method 3 Example Move Method 4 1 PUbliC C1055 ACCOUHt public class Account double overdraFtChargeO double bankChargeO return typeoverdraFtClIargedays0verdrawn double result 45 if daysOverd double bankChargeO result F double result 45 return result iF daysoverdrawn gt 0 result overdraFtChargeO private AccountType type return result private int daysOverdrawn 3 private AccountType type private int daysOverdrawn lass AccountType Removing source method requires updating all references to it oSource method body replaced With delegation Apply Inline Method oCode now compiles and can be used asis UNIVERSITY MASSACHUSETTS AMHERST Department of Computer Science Move Method Related Refactorings I Move Field I Move a field from source class to target class I Similar issues I Extract Class I Break up a single class into two classes I Create anew class that will contain some of the functionality of the source class I Create link between source and target class eg in constructor ofsource class I Move functionality to target class with repeated applications of Move Method and Move Field UNIVERSITY or MAssAcHusEns AMHERST Department of Computer Science
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'