Download Slides on Administrivia - Bioinformatics Algorithms, Databases, and Tools | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity! 22 CMSC 433 – Programming Language Technologies and Paradigms Spring 2004 Refactoring March 6, 2004 Lots of material taken from Fowler, Refactoring: Improving the Design of Existing Code 23 Administrivia • Project deadline Saturday, March 13 – Usual late rules apply • Minor (but important) project changes: – set_field methods should return the value of their parameter • Helps with EncapsulateField y in x = y = 1 – Can ignore +=, -=, *=, /= 24 Switch Statements • Usually not necessary in delegation-based OO programming • Replace Type Code with State/Strategy – Define a class hierarchy, a subclass for each type code • Replace Conditional with Polymorphism – Call method on state object to perform the check; switching is based on dynamic dispatch 25 Replace Type Code with State/Strategy 26 Replace Conditional with Polymorphism double getSpeed() { switch (kind) { case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed()-loadFactor()*numberOfCoconuts; case NORWEGIAN_BLUE: return (isNailed) ? 0 : getBaseSpeed(voltage); throw new RuntimeException(“Should be unreachable”); } } 27 Duplicated Code • The same expression used in different places in the same class – Use Extract Method to pull it out into a method • The same expression in two subclasses sharing the same superclass – Extract Method in each, then – PullUp method into parent • Duplicated code in two unrelated classes – Extract Class - Break a class that does many things into smaller classes 28 Pull Up Method • Might do other refactorings if methods don’t quite match • What if doesn’t appear in all subclasses? 29 Extract Class • How do we decide what goes in new class? • Do fields still need to be accessed in orig class? 30 Long Parameter List • Lots of parameters occlude understanding • Replace Parameter with Method – Remove method parameters and instead use some other way to get the parameter value (e.g., method call) • Introduce Parameter Object – Group parameters that go together into a container object 31 Replace Parameter with Method • discountedPrice can call getDiscount() itself double basePrice = num * price; double discount = getDiscount(); double finalPrice = discountedPrice(basePrice, discount); double basePrice = num * price; double finalPrice = discountedPrice(basePrice); 32 Introduce Parameter Object 33 Divergent Change • One class is commonly changed in different ways for different reasons – To add a new database, change these three methods – To add a new financial currency, change these four • Suggests maybe this shouldn’t be one object • Apply Extract Class to group together variations