Small changes to code to improve it. Refactoring Defined A change made to the internal structure of...

Post on 13-Jan-2016

214 views 0 download

Transcript of Small changes to code to improve it. Refactoring Defined A change made to the internal structure of...

RefactoringSmall changes to code to improve it

Refactoring DefinedA change made to the internal structure of

software to make it easier to understand and cheaper to modify without changing its observable behavior. — Refactoring, Martin Fowler. et. al. , page 53.Martin wrote the book:

RefactoringImproving the Design of Existing Code

Refactoring owes a lot to a Refactoring: William Opdyke's PhD thesis

Write Drafts and ReviseAll good writing is based upon revision.

— Jacques Barzun, Simple & Direct, 4th EditionRevision means "to look at again"Example: Before 4-July, 1776, Thomas Jefferson's

draft of the Declaration of Independence had this  "We hold these truths to be sacred and undeniable, ..."

He let his friend Benjamin Franklin look over this draft to make changes including this: "We hold these truths to be self-evident, ..."

Total of 47 revisions, then Congress made 39 morehttp://www.weeklyreader.com/googledocs/pdfs/revisionfiles.pdf

Refactoring HappensIn larger systems (frameworks), code will be read and

modified more frequently than it will be writtenRefactoring typically involves

Removing duplicated or dead codeSimplifying complex codeClarifying unclear code

It turns out that removing code can actually be a good thing: your system has fewer lines of codeEasier to develop, maintain, and change

Refactoring can be risky, unless you do it in small steps and have automated tests that can be run anytime

A few examplesA few refactorings we've seen (they have

names)Encapsulate Field (do this virtually always)

add getters and/or setters to access a fieldRename Method (often)Extract SuperClass (Shape and

AbstractStudent) You have two classes with similar features Create a superclass and move common features to the

superclassCompose Method

A variety of refactorings can happen at the method level

Compose MethodSome refactoring attempts to "compose"

methodsA composed method is relatively short by

using calls to a small number of coherent elementsEasier to understand what the method does

Some refactorings for composing methodsExtract MethodInline Method

Code demo: Compose insertElement in ArrayPriorityList

Before public void insertElementAt(int index, E el) { // If need to grow array, grow it if (size() == data.length) { Object[] temp = new Object[data.length + 20]; for (int i = 0; i < size; i++) temp[i] = data[i]; data = temp; }

// Shift array elements right to make room for (int j = size; j > index; j--) { data[j] = data[j - 1]; } // Add new element at the provided index data[index] = el; size++; }

After public void insertElementAt(int index, E el) { if (shouldGrowArray()) gowArray(); makeRoomAt(index); addAt(index, el); }

Is the new insertElementAt more readable?Vote: Yes: ____ Nay: _____

Are the extra private methods in the way? Vote: Yes: ____ Nay: _____

private void addAt(int index, E el) { data[index] = el; size++; }

private void makeRoomAt(int index) { for (int j = size; j > index; j--) { data[j] = data[j - 1]; } }

private void gowArray() { Object[] temp = new Object[data.length + 20]; for (int i = 0; i < size; i++) temp[i] = data[i]; data = temp; }

Replace Nested Conditional with Guard Clauses see link

private int scoreOf(String next) { int sum = 0; if (next.length() == 3 || next.length() == 4) sum = 1; else if (next.length() == 5) sum = 2; else if (next.length() == 6) sum = 3; else if (next.length() == 7) sum = 5; else if (next.length() >= 8) sum = 11; else sum = 0; return sum; }

Refactoring CatalogBuy the book or check out Martin's

Refactoring Catalog from the refactoring page http://www.refactoring.com/

Find catalog link and then find and read Inline Method

Next Tuesday, 1-Dec, I will ask you to read all 27 Refactorings on the next slide to prepare for test 2 on Thursday 3-DecI will give a sample test question follows the

list 27

 Read the following refactorings from

http://www.refactoring.com/catalog/index.html  (listed here in alphabetic order)

 Modifier

1. Add Parameter 2. Collapse Hierarchy 3. Consolidate Conditional

Expression 4. Consolidate Duplicate

Conditional Fragments 5. Decompose Conditional 6. Encapsulate Collection 7. Encapsulate Field8. Extract Class 9. Extract Method 10.Extract Superclass 11.Hide Method 12.Inline Method 13.Parameterize Method

Pull up Field14.Pull Up Method

15.Remove Double Negative16.Replace Assignment with

Initialization17.Replace Conditional with

Polymorphism18.Replace Inheritance with

Delegation 19.Replace Iteration with

Recursion 20.Remove Control Flag21.Replace Error Code with

Exception22.Replace Exception with Test23.Replace Magic Number with

Symbolic Constant 24.Replace Nested Conditional

with Guard Clauses 25.Replace Recursion with

Iteration 26.Reverse Conditional 27.Separate Query from Modifier

A dozen questions like thisg) Which design is better, I or II? Why? I void printOwing() { printBanner(); // print details System.out.println("name: " + _name); System.out.println("amount " + getOutstanding());}  

II void printOwing() { printBanner(); printDetails(getOutstanding());}

void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }

Answerg) II Why?If you have a code fragment that can be

grouped together, use Extract Method to turn the fragment into a method whose name explains the purpose of the method