Introduction to Refactoring

30
Introduction to Refactoring

description

Presentation given on 04 Oct 2009 at Barcamp PP2

Transcript of Introduction to Refactoring

Page 1: Introduction to Refactoring

Introduction to Refactoring

Page 2: Introduction to Refactoring

About Me

Vorleak ChyEmail ([email protected])Yoolk Inc. (http://www.yoolk.com)Blog (http://vorleakchy.com)Rails Developer.NET Developer

Page 3: Introduction to Refactoring

What do we talk about Refactoring?

What? Why?

When? How?

Page 4: Introduction to Refactoring

Get Agile – Refactoring

Practices

Tools

Page 5: Introduction to Refactoring

What is Refactoring?

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.

Fowler, et al., Refactoring, 1999.

Page 6: Introduction to Refactoring

Before

Unreadable codeDuplicated codeComplex codeHard to modify… More

After

Easier to understandClean codeBetter codeCheaper to modify… More

Page 7: Introduction to Refactoring

Why do we Refactor?

The realityExtremely difficult to get the design “right” the first timeHard to fully understand the problem domainHard to understand user requirements, even if the user does!Hard to know how the system will evolve in five yearsOriginal design is often inadequateSystem becomes brittle over time, and more difficult to change

Page 8: Introduction to Refactoring

Why do we Refactor? (Cont.)

Helps us to deliver more business values fasterImprove code structure and design

Easier to maintain and understandEasier to modifyMore flexibilityEasier to add new featuresIncreased re-usability

Page 9: Introduction to Refactoring

Why do we Refactor? (Cont.)

Keep development at speedTo make the software easier to understand

Write for people, not the compilerUnderstand unfamiliar code

To help us find bugsRefactor while debugging to clarify the code

Page 10: Introduction to Refactoring

Readability

Which code segment is easier to read?

if (date.before(Summer_Start) || date.after(Summer_End))charge = quantity * winterRate + winterServiceCharge;

elsecharge = quantity * summerRate;

Sample 1

Sample 2if (isSummer(date))

charge = summerCharge(quantity);else

charge = winterCharge(quantity);

Page 11: Introduction to Refactoring

When should we refactor?

Add new featuresFix bugsDuring code reviewOnly refactor when refactoring. Do not add features during refactoring

Page 12: Introduction to Refactoring

When Not to Refactor

Sometimes you should throw things out and start againSometimes you are too close to a deadline

Page 13: Introduction to Refactoring

Costs of Not Refactoring

Bad code usually takes more code to do the same thing often because of duplication

Page 14: Introduction to Refactoring

How do we Refactor?

We looks for Code-SmellsThings that we suspect are not quite right or will cause us severe pain if we do not fix

Page 15: Introduction to Refactoring

Common Code Smells

Duplicated codeFeature EnvyCommentsLong MethodLong parameter listSwitch Statements

Page 16: Introduction to Refactoring

Duplicated code

There is obvious duplicationSuch as copy and paste

There are unobvious duplicationsSuch as parallel inheritance hierarchiesSimilar algorithms

RemedyExtract MethodPull Up Field

Page 17: Introduction to Refactoring

Feature Envy

A method that seems more interested in some other classes than the one it is inRemedy

Move MethodExtract Method

Page 18: Introduction to Refactoring

Extract Methodvoid printOwning(double amount){

printBanner();

// print detailsSystem.Console.WriteLine(string.Format(“name: “, name);System.Console.WriteLine(string.Format(“amount: “, amount);

}

void printOwning(double amount){printBanner();printDetails(amount);

}

void printDetails(double amount){System.Console.WriteLine(string.Format(“name: “, name);System.Console.WriteLine(string.Format(“amount: “, amount);

}

Page 19: Introduction to Refactoring

Comments

Comments – be suspicious!Comments represent a failure to express an idea in the codeRemedy

Extract MethodRename Method

Page 20: Introduction to Refactoring

Long Method

Good OO code is easiest to understand and maintain with shorter methods with good namesLong methods tend to be harder to read and understandRemedy

Extract MethodReplace Temp with QueryReplace Method with Method ObjectDecompose Conditional

Page 21: Introduction to Refactoring

Replace Temp with Query

double basePrice = _quanity *_itemPrice;

if(basePrice > 1000) {return basePrice * 0.95;

}else {

return basePrice * 0.98;}

if(getBasePrice() > 1000) {return getBasePrice() * 0.95;

}else {

return getBasePrice() * 0.98;}

double getBasePrice() {return _quanitiy * _itemPrice;

}

Page 22: Introduction to Refactoring

Long parameter list

Functions should have as few parameters as possibleRemedy

Replace Parameter with MethodPreserve Whole ObjectIntroduce Parameter Object

Page 23: Introduction to Refactoring

Introduce Parameter Object

amountInvoicedIn(Date start, Date end)amountRecivedIn(Date start, Date end)amountOverdueIn(Date start, Date end)

Customer

amountInvoicedIn(DateRange range)amountRecivedIn(DateRange range)amountOverdueIn(DateRange range)

Customer

Page 24: Introduction to Refactoring

Switch Statements

Type cases are evil because they tend to be duplicated many timesRemedy

Replace Type Code with SubclassesReplace Type Code with State / StrategyReplace Conditional with PolymorphismReplace Parameter with Explicit MethodsIntroduce Null Object

Page 25: Introduction to Refactoring

Replace Parameter with Explicit Methods

void setValue(String name, int value){

if(name.Equals(“height”)){

_height = value;return;

}if(name.Equals(“width”)){ _width = value;

return; }

}

void setHeight(int value){

_height = value;}

void setWidth(int value){

_width = value;}

Page 26: Introduction to Refactoring

Refactoring Cycle

Choose on appropriate Refactoring

to apply

Apply Refactoring

Run ALL Tests (Get GREEN

Bar)

No

Yes

Reached Desired

Structure?

Page 27: Introduction to Refactoring

Demo

Page 28: Introduction to Refactoring

Q & A

Page 29: Introduction to Refactoring

Essential Reading

Page 30: Introduction to Refactoring

Thank you!