30
Refactoring Refactoring Improving the Design of Existing Improving the Design of Existing Code Code MELJUN CORTES MELJUN CORTES MELJUN CORTES MELJUN CORTES

MELJUN CORTES Java Lecture Refactoring

Embed Size (px)

DESCRIPTION

MELJUN CORTES Java Lecture Refactoring

Citation preview

Page 1: MELJUN CORTES Java Lecture Refactoring

RefactoringRefactoring

Improving the Design of Existing CodeImproving the Design of Existing Code

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Java Lecture Refactoring

Topic CoverageTopic Coverage

Background of refactoringBackground of refactoring What is Refactoring?What is Refactoring? Where it came fromWhere it came from

Principles in RefactoringPrinciples in Refactoring The Two Hats MetaphorThe Two Hats Metaphor Why and WhenWhy and When Refactoring and DesignRefactoring and Design Refactoring and PerformanceRefactoring and Performance

Page 3: MELJUN CORTES Java Lecture Refactoring

Topic Coverage (cont.)Topic Coverage (cont.)

Bad SmellsBad Smells What is code smell?What is code smell? Types of code smellsTypes of code smells

Types of RefactoringTypes of Refactoring Types of refactoring.Types of refactoring.

Page 4: MELJUN CORTES Java Lecture Refactoring

Background of Background of RefactoringRefactoring

What is Refactoring?What is Refactoring?

Where it came fromWhere it came from

Page 5: MELJUN CORTES Java Lecture Refactoring

What is Refactoring?What is Refactoring?

Disciplined way to codeDisciplined way to code Over time code will be modifiedOver time code will be modified Changing code in small stepsChanging code in small steps Verify no change in external behavior byVerify no change in external behavior by

– – TestingTesting

– – Formal code analysis by toolFormal code analysis by tool

Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.

Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.

Page 6: MELJUN CORTES Java Lecture Refactoring

Where Refactoring Came Where Refactoring Came From?From?

Ward Cunningham and Kent BeckWard Cunningham and Kent BeckSmalltalk styleSmalltalk style

Ralph Johnson at University of Illinois atRalph Johnson at University of Illinois atUrbana-ChampaignUrbana-Champaign

Bill Opdyke’s ThesisBill Opdyke’s Thesisftp://st.cs.uiuc.edu/pub/papers/ftp://st.cs.uiuc.edu/pub/papers/refactoring/opdyke-thesis.ps.Zrefactoring/opdyke-thesis.ps.Z

John Brant and Don Roberts: The John Brant and Don Roberts: The Refactoring BrowserRefactoring Browser

Page 7: MELJUN CORTES Java Lecture Refactoring

Principles in Principles in RefactoringRefactoring

The Two Hats MetaphorThe Two Hats Metaphor

Why and WhenWhy and When

Refactoring and DesignRefactoring and Design

Refactoring and PerformanceRefactoring and Performance

Page 8: MELJUN CORTES Java Lecture Refactoring

The Two Hats MetaphorThe Two Hats Metaphor

Adding Function

• Add new capabilities to the system• Adds new tests• Get the test working

Refactoring

• Does not add anynew features• Does not add tests(but may change some)• Restructure the codeto remove redundancy

Swap frequently between the hats,but only wear one at a time

Page 9: MELJUN CORTES Java Lecture Refactoring

Why Refactor?Why Refactor?

To improve the software designTo improve the software design Combat’s “bit rot”Combat’s “bit rot” Makes the program easier to changeMakes the program easier to change

To make the software easier to understandTo make the software easier to understand Write for people, not the compilerWrite for people, not the compiler Understand unfamiliar codeUnderstand unfamiliar code

To help find bugsTo help find bugs Refactor while debugging to clarify the codeRefactor while debugging to clarify the code

Refactoring helps you program faster.Refactoring helps you program faster.

Page 10: MELJUN CORTES Java Lecture Refactoring

When to Refactor?When to Refactor?

To add new functionalityTo add new functionality Refactor existing code until you Refactor existing code until you

understand itunderstand it Refactor the design to make it easy to Refactor the design to make it easy to

addadd To find bugsTo find bugs

Refactor to understand the codeRefactor to understand the code For code reviewsFor code reviews

Immediate effect of code reviewImmediate effect of code review Allows for higher level suggestionsAllows for higher level suggestions

Don’t set aside time for refactoring,include it in your normal activities

Page 11: MELJUN CORTES Java Lecture Refactoring

Refactoring and DesignRefactoring and Design

Special role as a complement to Special role as a complement to design.design.

Refactoring can be an alternative to Refactoring can be an alternative to upfront designupfront design

Refactoring can lead to simpler Refactoring can lead to simpler design without sacrificing flexibilitydesign without sacrificing flexibility

Page 12: MELJUN CORTES Java Lecture Refactoring

Refactoring and Refactoring and PerformancePerformance

Refactoring make software go more Refactoring make software go more slowlyslowly

Refactoring makes the software more Refactoring makes the software more amenable to performance tuningamenable to performance tuning

Well refactored program gives you time to Well refactored program gives you time to spend on performance tuningspend on performance tuning

Well refactored program you have finer Well refactored program you have finer granularity for you performance analysisgranularity for you performance analysis

The best way to optimize performance is to first writea well factored program, then optimize it.

Page 13: MELJUN CORTES Java Lecture Refactoring

Types of RefactoringTypes of Refactoring

Page 14: MELJUN CORTES Java Lecture Refactoring

Extract MethodExtract Method

You have a code fragment that can be grouped togetherTurn the fragment into a method whose name explains the

Purpose of the method.

void printOwing(double amount){ printBanner(); //printDetails System.out.println(“name:”+ _name); System.out.println(“amount:”+ amount);}

void printOwing(double amount){ printBanner(); printDetails(amount); }

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

Page 15: MELJUN CORTES Java Lecture Refactoring

Inline MethodInline Method

A method’s body is just as clear as its name

Put the method’s body in 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;}

Page 16: MELJUN CORTES Java Lecture Refactoring

Inline TempInline Temp

You have a temp that assigned to once with a simple expression,and the temp is getting in the way of other refactorings.

Replace all references to that temp with the expression

double basePrice – anOrder.basePrice();return (basePrice > 1000)

return (anOrder.basePrice() > 1000)

Page 17: MELJUN CORTES Java Lecture Refactoring

Replace Temp with Replace Temp with QueryQuery

You are using a temporary variable to hold the result of an expression

Extract the expression into a method. Replace all references to the tempwith the expression. The new method can then be

used in other methods.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;}

Page 18: MELJUN CORTES Java Lecture Refactoring

Introduce Explaining Introduce Explaining VariableVariable

You have a complicated expression

Put the result of the expression, or parts of the expression, in atemporary variable with a name that explains the purpose.

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 = platform.toUpperCase().indexOf(“IE”) > -1;final boolean wasResized = resize > 0;

if (isMacOs && isIEBrowser && wasInitialized() && wasResized) {

//do something}

Page 19: MELJUN CORTES Java Lecture Refactoring

Move MethodMove Method

A method is, or will be, using or used by more features of another class that the class on which it

is defined

Create a new method with a similar body in the class it uses most.Either turn the old method into a simple delegation, or

remove it altogether.

Class 1

aMethod()

Class 2

Class 1

Class 2

aMethod()

Page 20: MELJUN CORTES Java Lecture Refactoring

Move FieldMove Field

A field is, or will be, used by another class more than the classon which it is defined.

Create a new field in the target class, and change all its users.

Class 1

aField

Class 2

Class 1

Class 2

aField

Page 21: MELJUN CORTES Java Lecture Refactoring

Extract ClassExtract Class

You have one class doing work that should be done by two.

Create a new class and move the relevant fields and methodsFrom the old class into the new class

Person

nameofficeAreaCodeofficeNumber

getTelephoneNumber()

Person

name

getTelephoneNumber()

Telephone Number

areaCodenumber

getTelephoneNumber()

officeTelephone

1

Page 22: MELJUN CORTES Java Lecture Refactoring

Inline ClassInline Class

A class isn’t doing very much

Move all its features into another class and delete it.

Person

nameofficeAreaCodeofficeNumber

getTelephoneNumber()

Person

name

getTelephoneNumber()

Telephone Number

areaCodenumber

getTelephoneNumber()

officeTelephone

1

Page 23: MELJUN CORTES Java Lecture Refactoring

Pull Up FieldPull Up Field

Two subclasses have the same field

Move the field to the superclass.

Employee

Salesman

name

Engineer

name

Employee

name

EngineerSalesman

Page 24: MELJUN CORTES Java Lecture Refactoring

Pull Up MethodPull Up Method

You have methods with identical results on subclass

Move them to the superclass

Employee

Salesman

getName()

Engineer

getName()

Salesman

Employee

getName()

Engineer

Page 25: MELJUN CORTES Java Lecture Refactoring

Pull Up Constructor BodyPull Up Constructor Body

You have constructor on subclasses with mostlyIdentical bodies.

Create a superclass constructor; call this from thesubclass methods

class Manager extends Employee ... public Manager (String name, String id, int grade) { _name = name; _id = id; _grade = grade; }

public Manager (String name, String id, int grade) { super(name, id); _grade = grade; }

Page 26: MELJUN CORTES Java Lecture Refactoring

Push Down MethodPush Down Method

Behavior on a superclass is relevant only for some of its subclasses

Move it to those subclasses

Employee

Salesman

getQuota()

EngineerSalesman

Employee

getQuota()

Engineer

Page 27: MELJUN CORTES Java Lecture Refactoring

Push Down FieldPush Down Field

Two subclasses have the same field

Move the field to the superclass.

Employee

Salesman

quota

Engineer

Employee

quota

EngineerSalesman

Page 28: MELJUN CORTES Java Lecture Refactoring

Rename MethodRename Method

The name of a method does not reveal its purpose.

Change the name of the method

Customer

getinvcdtlmt()

Customer

getInvoiceCreditLimit()

Page 29: MELJUN CORTES Java Lecture Refactoring

Add ParameterAdd Parameter

A method needs more information from its caller.

Add a parameter for an object that can pass onthis information.

Customer

getContact()

Customer

getContact(:Date)

Page 30: MELJUN CORTES Java Lecture Refactoring

Remove ParameterRemove Parameter

A parameter is no longer used by the method body.

Remove it

Customer

getContact()

Customer

getContact(:Date)