1 Software Maintenance and Evolution CSSE 575: Session 2, Part 2 Composing Methods Steve Chenoweth Office Phone: (812) 877-8974 Cell: (937) 657-3885 Email:

Slides:



Advertisements
Similar presentations
A practical guide John E. Boal TestDrivenDeveloper.com.
Advertisements

About Me – Frank Xu Education ▫ North Dakota State University  Ph.D. in Software Engineering ▫ Towson University  MS in Computer Science ▫ Southeast.
Software Testing and Maintenance 1 Today’s Agenda  Course Evaluation  HW 4 Return  HW 5 Correction  Quiz 4 Next Class  Software Refactoring.
Refactoring: Improving the Design of Existing Code © Martin Fowler, Martin Fowler.
Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative to refactoring.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 4 Big Refactorings Steve Chenoweth Office Phone: (812) Cell: (937)
Software Engineering Key Refactorings
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 3 Moving Features Between Objects Steve Chenoweth Office Phone: (812) Cell: (937)
XP2007b Extreme Code Quality Dongsu Park Venkatesh BS.
Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.
George Blank University Lecturer. REFACTORING Improving the Design of Existing Code Supplement to Ian Sommerville, Software Engineering, Chapter 20 Prepared.
25-Jun-15 Refactoring III. General philosophy A refactoring is just a way of rearranging code Refactorings are used to solve problems If there’s no problem,
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
Algorithm Programming Coding Advices Bar-Ilan University תשס " ו by Moshe Fresko.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Fruitful functions. Return values The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these.
Refactoring – III Measured Smells. Smells Covered 1. Comments 2. Long method 3. Large Class 462.
Program Refactoring Mitch Soden Union College. Agenda Definition –Unit Testing –Examples Why Refactor? Limitations Just Another SW Eng Practice? Automation.
Refactoring and its role in Test-Driven Development Miguel J. T. Pessoa Monteiro Escola Superior de Tecnologia de Castelo Branco.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring - A disciplined approach to rework for better design.
Refactoring Improving the structure of existing code Refactoring1.
Chapter 7: Bad Code Smells Omar Meqdadi SE 3860 Lecture 7 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Small changes to code to improve it. Refactoring Defined A change made to the internal structure of software to make it easier to understand and cheaper.
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.
Improving the Quality of Existing Code Svetlin Nakov Telerik Corporation
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 1 Simplifying Conditionals Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring1 Improving the structure of existing code.
Agile Software Development Lab Spring 2008 R O O T S 1 Sina Thomas ) XP: Extreme.
Hesam C. Esfahani Lecture 8 Code Refactoring CSC301-Winter 2011.
Introduction to Refactoring Jim Cooper Falafel Software.
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
Refactoring. Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative.
Chapter 21 Test-Driven Development 1CS6359 Fall 2011 John Cole.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
NJIT 1 Test Driven Development and Refactoring Larman, Chapter 21.
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 1 Refactoring Principles Steve Chenoweth Office Phone: (812) Cell: (937)
Software Construction and Evolution - CSSE 375 Making Method Calls Simpler Shawn and Steve Below – “Be the character!” The late acting teacher Lee Strasberg.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization Steve Chenoweth Office Phone: (812) Cell: (937)
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Refactoring Advanced Software Engineering Dr Nuha El-Khalili.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring1 Improving the structure of existing code.
Software Construction and Evolution - CSSE 375 Simplifying Conditionals Shawn & Steve.
Refactoring Constants and Variables Lesson Three: Constants and Variables.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Software Construction and Evolution - CSSE 375 Dealing with Generalization Steve and Shawn Left – In the 1990 movie “The Freshman,” Matthew Broderick,
Refactoring. DCS – SWC 2 Refactoring ”A change made to the internal structure of software to make it easier to understand and cheaper to modify without.
Topic 6 loops, figures, constants Based on slides bu Marty Stepp and Stuart Reges from "Complexity has and will maintain.
WARNING These slides are not optimized for printing or exam preparation. These are for lecture delivery only. These slides are made for PowerPoint 2010.
Code Refactoring Milan Vukoje Soprex SkfOffice2 SkfOffice3 Big5 Quality oriented We are hiring…
Catalog of Refactoring (1) Composing Methods. Code Smells Long methods Dubious temporary variables Dubious methods.
ICONFINDER ICONFINDER Founded Django based web application -PostgreSQL -Elasticsearch -Amazon Elastic Compute.
Catalog of Refactoring (6) Making Method Calls Simpler.
Refactoring (1). Software Evolution Cope with change Feature bloat Design decay Code duplications “Pattern time is refactoring time” Make future changes.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Principles and examples
Catalog of Refactoring
Steve Chenoweth Office Phone: (812) Cell: (937)
Refactorings Luke Marsh.
Refactoring with inline temp, method, and class
Software Construction and Evolution - CSSE 375 Composing Methods
Introduction to Refactoring
Improving the structure of existing code
Building Java Programs
Topic 6 loops, figures, constants
Building Java Programs
Building Java Programs
Presentation transcript:

1 Software Maintenance and Evolution CSSE 575: Session 2, Part 2 Composing Methods Steve Chenoweth Office Phone: (812) Cell: (937) Wagner composing – from

2 Shu Ha Ri Shuhari roughly translates to "first learn, then detach, and finally transcend." shu ( 守 ) "protect", "obey" — traditional wisdom — learning fundamentals, techniques, heuristics, proverbs ha ( 破 ) "detach", "digress" — breaking with tradition — detachment from the illusions of self ri ( 離 ) "leave", "separate" — transcendence — there are no techniques or proverbs, all moves are natural, becoming one with spirit alone without clinging to forms; transcending the physical From Japanese martial arts, originally. Description from Pic from Refactoring - level of skill: CSSE CSSE 375 (where we now teach refactoring) CSSE 575 & In Industry

3 Composing Methods Refactoring deals a lot with composing methods to properly package code Refactor methods that are too long or do too much These refactorings are all more specific solutions than the ones we recommended generally for the bad smells.  Extract Method  Inline Method  Inline Temp  Replace Temp with Query  Introduce Explaining Variables  Split Temporary Variable  Remove Assignments to Parameters  Replace Method with Method Object  Substitute Algorithm  Extract Method  Inline Method  Inline Temp  Replace Temp with Query  Introduce Explaining Variables  Split Temporary Variable  Remove Assignments to Parameters  Replace Method with Method Object  Substitute Algorithm

4 Extract Method Situation: You have a code fragment that can be grouped together – Method is too long – Needs Clarity – comments to reflect purpose – Undue redundancy Solution: Turn fragment into a method whose name explains the purpose of the method – Shorter well-named methods – Can be used by other methods – Higher-level methods read more like a series of comments

5 Exact Method: Simple Example void printOwing() { printBanner(); //print details System.out.println("name: " + _name); System.out.println("amount: " + amount); } Clue - bird landing

6 Extract Method: Simple Example void printOwing() { printBanner(); printDetails(amount); } void printDetails (double amount) { System.out.println ("name: " + _name); System.out.println ("amount " + amount); }

7 Mechanics Create a new method and name it after “what it does” – it’s intention Copy extracted code from source into target Scan extracted method for references to any variables that are local to the source method – Local variables /parameters to the target method Check for temporary variables used within extracted code – If present, declare them in the target method as temporary variables

8 Mechanics (continued) Check for local-scope variables modified by extracted code – 1 modified variable: treat extracted code as query and assign result to variable concerned – More than 1 variable: can’t extract method From extracted code, pass local-scope variables into target as parameters Replace extracted code in source method with a call to target method Compile and test

9 More Detailed Example void printOwing() { Enumeration e = _orders.elements(); double outstanding = 0.0; // print banner System.out.println ("**************************"); System.out.println ("***** Customer Owes ******"); System.out.println ("**************************"); // calculate outstanding while (e.hasMoreElements()) { Order each = (Order) e.nextElement(); outstanding += each.getAmount(); } //print details System.out.println ("name:" + _name); System.out.println ("amount" + outstanding); } Problem 3 Problem 1 Problem 2

10 More Detailed Example – Extract 2 Methods void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); } void printBanner() { // print banner System.out.println ("**************************"); System.out.println ("***** Customer Owes ******"); System.out.println ("**************************"); } Extract 2 Extract 3

11 More Detailed Example – Extract Orders void printOwing() { double outstanding = getOutstanding(); printBanner(); PrintDetails(outstanding); } double getOutstanding() { Enumeration e = _orders.elements(); double outstanding = 0.0; while (e.hasMoreElements()) { Order each = (Order) e.nextElement(); outstanding += each.getAmount(); } return outstanding; } void printDetails (double outstanding) { … } void printBanner() {… } Extract 1

12 More Detailed Example – Extracted Methods void printOwing() { double outstanding = getOutstanding(); printBanner(); PrintDetails(outstanding); } double getOutstanding() { Enumeration e = _orders.elements(); double outstanding = 0.0; while (e.hasMoreElements()) { Order each = (Order) e.nextElement(); outstanding += each.getAmount();} return outstanding; } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); } void printBanner() { System.out.println ("**************************"); System.out.println ("***** Customer Owes ******"); System.out.println ("**************************"); } Extract 1 Extract 2 Extract 3

13 Exercise – Reassign a Local Variable void printOwing() { double outstanding = getOutstanding(); printBanner(); PrintDetails(outstanding); } double getOutstanding() { Enumeration e = _orders.elements(); double outstanding = 0.0; while (e.hasMoreElements()) { Order each = (Order) e.nextElement(); outstanding += each.getAmount(); } return outstanding; } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); } void printBanner() { System.out.println ("**************************"); System.out.println ("***** Customer Owes ******"); System.out.println ("**************************"); }

14 Example: Reassigning a Local Variable Outstanding used in both places (main method and the new getOutstandin g we extracted) – We need to return it from the extracted method Outstanding is initialized only to an obvious initial value (0.0) – C an initialize it only within the extracted method – If something more involved happens to the variable, we have to pass in the previous value as a parameter  See next slide!

15 Exercise – Reassigned a Local Variables void printOwing(double previousAmount) { double outstanding = previousAmount; printBanner(); double outstanding = getOutstanding(); PrintDetails(outstanding); } double getOutstanding(double initialValue) { Enumeration e = _orders.elements(); double result = initialValue; while (e.hasMoreElements()) { Order each = (Order) e.nextElement(); result += each.getAmount(); } return result; } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); } void printBanner() { System.out.println ("**************************"); System.out.println ("***** Customer Owes ******"); System.out.println ("**************************"); }

16 Inline Method Situation: A method’s body is as clear as its name – why have the method? – Use short methods – Needless Indirection Solution: Put the method’s body into the the body of its callers and remove the method int getRating() { return (moreThanFiveLateDeliveries()) ? 2 :1; } boolean moreThanFiveLateDeliveries() return _numberOfLateDeliveries > 5; } int getRating() { return (_numberOfLateDeliveries > 5) ? 2 :1; }

17 Inline Temp Situation: Temp assigned to once with a simple expression, and temp getting in the way of other refactorings? Solution: Replace all references to the temp with the expression. double basePrice = anOrder.basePrice(); return (basePrice > 100); … return (anOrder.basePrice() > 100); …

18 Replace Temp with Query Situation: Using a temporary variable to hold the result of an expression unnecessarily Solution: Extract the expression into a method. Replace all references to the temp with the expression. double basePrice = _quantity * _itemPrice; if (basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98; … if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98;... double basePrice() { return _quantity * _itemPrice; }

19 Introduce Explaining Variable Situation: You have a complicated expression. Solution: Put result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose. 19 if ( (platform.toUpperCase().indexOf("MAC") > -1) && (browser.toUpperCase().indexOf("IE") > -1) && wasInitialized() && resize > 0 ) { // do something } final boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1; final boolean isIEBrowser = browser.toUpperCase().indexOf("IE") > -1; final boolean wasResized = resize > 0; if (isMacOs && isIEBrowser && wasInitialized() && wasResized) { // do something }

20 Split Temporary Variables Situation: Have a temporary variable assigned to more than once – Exception: Not a loop variable, nor a collecting temporary variable Solution: Make a separate temporary variable for each assignment double temp = 2 * (_height + _width); System.out.println (temp); temp = _height * _width; System.out.println (temp); final double perimeter = 2 * (_height + _width); System.out.println (perimeter); final double area = _height * _width; System.out.println (area);

21 Remove Assignments to Parameters Situation: The code assigns to a parameter. Solution: Use a temporary variable instead. int discount (int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; int discount (int inputVal, int quantity, int yearToDate) { int result = inputVal; if (inputVal > 50) result -= 2;