Class Note for CMPSCI 220 at UMass(1)
Class Note for CMPSCI 220 at UMass(1)
Popular in Course
Popular in Department
This 8 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 14 views.
Reviews for Class Note for CMPSCI 220 at UMass(1)
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
Flyweight Pattern I Use wlien one instance Of a class can serve as many Virtual instances CMPSCI 220 291A Programming Methodology Spring 2009 I Reduces number ofobject instances saves space I At runtime I In stable storage database file system etc I Centralizes state for many Virtual objects 18 Flyweight Pattern amp Refactoring with thanks to Frank Tip I HFDP means this one way I Alternative interpretation probably more common I Used when a class has many instances and they can all be controlled identically r HFDP I An abroaderinte retation robabl better UNIVERsmr or MASSACHUSETTS AMHERST Department of Comtpuhar Science 7 Umvrnsm or MASSAcHusnrs AMHERST Department creompttersaenee HFDP s Flyweight Example More Typical Flyweight Example Tree TreeManager Tree Tree Tree TreeInfo XC rd treeArray displayx y age XC rd xCoord arge amount YCOOrd displayTrees use XY coords YCOOrd yCoord of data common age for all trees amp complex age age age to all or some dlSPIaYO get array row reated calcs large amount myInfo trees use XY coords display y age of data common amp complex age to all or some 0 Each Tree instance 0 One single reated calcs one singel trees points to one shared lmmUtable statefree copy of common data Treelnfo Tree object ObJeCt 0 Each Tree instance maintains its own copy of common data 0 State for all virtual Tree objects stored in treeArray 0 Each Tree instance maintains its own state iiJNIVERsnY o mgsACHLISE ITS AMHERST Department of Computer Science UNIVERSITYioFliIASSACHLISFTTS AMHERST Department of Computer Science What is Refactoring Refactorings Two Key Features I Process of applying transformations I Small steps refactorings to a program Typically many I Goal is improving its design while I Methodical transformation process I Keeping program readable understandable and I BehaViOr39PreserVing maintainable I Make sure the program works after each step I By eliminating small problems early avoid big trouble later UNIVERSITY or MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY or MAssAcHusHTs AMHERST Department of Campmer Science Reasons for Refactoring I Change to requirements necessitates different design I Desire to make design more exible I Design patterns are often target for refactoring I Programmer sloppiness I Cut and paste introduction of a new method I Programmers don t come up with right design the first time I Sometimes intentionally agile development methods like XP call for continuous refactoring UNIVERSITY OF MASSACHUSEl ITS AMHERST Department of Computer Science Extract Method How I Create a new method invent a name for it I Pick a name describing what the method does I Copy extracted code from source method to new target method I Eclipse will do it for you UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science Example Extract Method Void printowing Enumeration e orderselements double outstanding 00 I I 5 MW a x I I ntln u I in rm tttttttt tt calculate outstanding while ehasMoreElements Order each 0rderenextElement outstanding eachgetAmount print details Systemoutprintln name name Systemoutprintln amount outstanding UNIVERSITY MASSACHUSETTS AMHERST Department of Computer Science Refactoring Extract Metho I Refactoring for extracting a code fragment into a method I Goals I Enable reuse I Avoid cuteandepaste programming I Make longer methods shorter and more readable UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Scienee Extract Method How I Scan extracted code for variables local in scope to source method or let Eclipse I Only used in target method declare in target method 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 Example Extract Method 2 void printowing Enumeration e orderselements double outstanding 00 printBannerO calculate outstanding while ehasMoreElements Order each 0rderenextElement outstanding eachgetAmount public void printBannerO system utprin m ttttttttttttttttttttttttt Systemoutprintln Customer Owes system utprin m ttttttttttttttttttttttttt 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 7 UNIVERSITY MAsgAEImssns AMHERST Department of Computer ecience Extract Method Considerations Problem Case 39 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 r UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Sciense Inverse of Extract Method Refactoring Inline Method Replace Temp with Query I Replace method call with body of called method I Commonly applied by optimizing compilers I When to apply Eclipse will do this tool I As an intermediate step when a group of methods is badly I HOW factored I Goal Eliminate temporary variable used to hold result of an expression I If too much delegation makes code hard to follow I Dedare Item ZS F1 nail an recomPlle I I Various complica ng issues I Compiler Will alert you if multiple ass1gnments eXist I Polymorphic call sites I Extract the expression into a method I Recursion I Replace all references to the temp With calls to I Multiple return points that method UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer Science 2 UNIVERSITY OF MASSACHUSETTS AMHERST Department of Computer 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 UNIVERSITY MASSACHUSHTS AMHERST Department of Computer Science UNIVERSITY MASSAcnusnrs AMHERST 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 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 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 7 UNIVERSITY MAEAJISHTS 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'