Your SlideShare is downloading. ×
0
Java
Refactoring Fest
          Naresh Jain
     naresh@agilefaqs.com



  Licensed Under Creative Commons by Naresh Jain
...
Tutorial Schedule


What, Why, When and How... Refactor?
How to Refactor to Patterns
How to deal with Legacy Code?
Refacto...
Three Golden Rules


Once and only once [DRY]
Express intent
Tell, don’t ask




                  Licensed Under Creative...
Definitions
Loose Usage
 Reorganize a program (or something)
As a noun
 a change made to the internal structure of some sof...
What is Refactoring?
       small steps, each of which changes the program’s
A series of
internal structure without changi...
What if you hear...

We’ll just refactor the code to add logging support
Can you refactor the code so that it authenticate...
Origin
Ward Cunningham and Kent Beck
 Smalltalk style
Ralph Johnson at University of Illinois at Urbana-
Champaign
Bill Op...
Why do we Refactor?
Helps us deliver more business value faster
Improves the design of our software
 Combat’s “bit rot”
 E...
Why do we Refactor?...
Minimizes technical debt
Keep development at speed
To make the software easier to understand
 Write...
Readability
Which code segment is easier to read?
Sample 1
if (date.before(Summer_Start) || date.after(Summer_End)){

 cha...
When should you refactor?

To add new functionality
 refactor existing code until you understand it

                 Like...
The Two Hats
Adding Function
                                                         Refactoring



Add new capabilities ...
Refactoring and TDD
                                                        Add a Test


                                 ...
Team Techniques


Encourage refactoring culture
 nobody gets things right first time
 nobody can write clear code without r...
Team Techniques...

Provide sound testing base
 tests are essential for refactoring
 build system and run tests daily
Pair...
How do we Refactor?


We looks for Code-Smells
Things that we suspect are not quite right or will cause us severe pain if
...
Common Code Smells
The Big Stinkers
   Duplicated code                           Long Method
   Feature Envy              ...
Duplicated Code
There is obvious duplication
 Such as copy and paste
There are unobvious duplications
 Such as parallel in...
Feature Envy

A method that seems more interested in some other class than the one
it is in.
Remedies:
 Move Method
 Extra...
Extract Method
void printOwning(double amount){
    printBanner();

    // print details
    System.Console.WriteLine(stri...
Inappropriate Intimacy


Two or more classes fiddling with each other’s private parts.
Remedies
 Move Method and Move Field...
Extract Class

      Person                           Person                  TelephoneNumber
name
officeAreaCode         ...
Comments
Comments – be suspicious!
Comments are a deodorant.
Comments represent a failure to express an idea in the code.
...
Introduce Assertion
double GetExpenseLimit() {
   // should have either expense limit or a primary project
   return(_expe...
Long Method

Good OO code is easiest to understand and maintain with shorter
methods with good names
Long methods tend to ...
Replace Temp with Query
double basePrice = _quanity *           if(getBasePrice() > 1000) {
     _itemPrice;              ...
Long parameter list

Functions should have as few parameters as possible.
Remedies:
 Replace Parameter with Method
 Preser...
Introduce Parameter Object
             Customer
AmoutInvoicedIn(Date start, Date end)
AmoutRecivedIn(Date start, Date end...
Switch Statements
Type cases are evil because they tend to be duplicated many times.
Remedies:
 Replace Type Code with Sub...
Replace Parameter
            with Explicit Methods
void SetValue(String name, int value) void SetHeight(int value)
{     ...
Inappropriate Naming
Names given to variables (fields) and methods should be
clear and meaningful.
A variable name should s...
Refactoring & Patterns


There is a natural relation between patterns and refactorings. Patterns
are where you want to be;...
Refactoring to Patterns

Creation – creation of objects
Simplification – code simplification
Generalization – code abstracti...
How to refactor Legacy Code?
Identify change points
Find an inflection point
Cover the inflection point
 Break external depe...
Essential Reading




Licensed Under Creative Commons by Naresh Jain
                                                 35
Refactoring Hands-on


We’ll use an open source project to apply refactoring lessons
Make sure your laptops are setup with...
Refactoring Hands-on...

You will be introduced to 2-3 code smells at a time
Apply lessons form working with legacy code t...
Thank you
    Java Refactoring Fest

        Naresh Jain
   naresh@agilefaqs.com


Licensed Under Creative Commons by Nare...
Upcoming SlideShare
Loading in...5
×

Refactoring Fest

14,148

Published on

Intent of this tutorial is to provide the participants with a hands-on-experience of real world refactoring by taking an open source project and refactoring it.
Benefits

After attending this session, the participants should be able to:
Build a common vocabulary in the refactoring space
Identify code smells
Eliminate code smells by applying the simple refactoring techniques explained in Martin Fowler‘s “Refactoring”
Write better unit/functional tests for legacy code
Understand some of the techniques and pitfalls in refactoring legacy code in the absence of unit and functional tests [”Working effectively with legacy code “]
Take existing code and refactor it to standard design patterns [Refactoring to patterns]
Learn about the internals of the open source project chosen to refactor
Know where to look to continue learning the techniques of refactoring

Published in: Technology, Spiritual
0 Comments
15 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
14,148
On Slideshare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
361
Comments
0
Likes
15
Embeds 0
No embeds

No notes for slide

Transcript of "Refactoring Fest"

  1. 1. Java Refactoring Fest Naresh Jain naresh@agilefaqs.com Licensed Under Creative Commons by Naresh Jain 1
  2. 2. Tutorial Schedule What, Why, When and How... Refactor? How to Refactor to Patterns How to deal with Legacy Code? Refactoring Hands-on session Licensed Under Creative Commons by Naresh Jain 2
  3. 3. Three Golden Rules Once and only once [DRY] Express intent Tell, don’t ask Licensed Under Creative Commons by Naresh Jain 3
  4. 4. Definitions Loose Usage Reorganize a program (or something) As a noun a change made to the internal structure of some software to make it easier to understand and cheaper to modify, without changing the observable behavior of that software As a verb the activity of restructuring software by applying a series of refactorings without changing the observable behavior of that software. Licensed Under Creative Commons by Naresh Jain 4
  5. 5. What is Refactoring? small steps, each of which changes the program’s A series of internal structure without changing its external behavior - Martin Fowler Verify no change in external behavior by Testing Using the right tool - IDE Formal code analysis by tool Being very, very careful Licensed Under Creative Commons by Naresh Jain 5
  6. 6. What if you hear... We’ll just refactor the code to add logging support Can you refactor the code so that it authenticates against LDAP instead of Database? We have too much duplicate code, we need to refactor the code to eliminate duplication This class is too big, we need to refactor it Caching? Licensed Under Creative Commons by Naresh Jain 6
  7. 7. Origin Ward Cunningham and Kent Beck Smalltalk style Ralph Johnson at University of Illinois at Urbana- Champaign Bill Opdyke’s Thesis ftp://st.cs.uiuc.edu/pub/papers/refactoring/opdyke- thesis.ps.Z John Brant and Don Roberts: The Refactoring Browser Licensed Under Creative Commons by Naresh Jain 7
  8. 8. Why do we Refactor? Helps us deliver more business value faster Improves the design of our software Combat’s “bit rot” Easier to maintain and understand Easier to facilitate change More flexibility Increased re-usability Licensed Under Creative Commons by Naresh Jain 8
  9. 9. Why do we Refactor?... Minimizes technical debt Keep development at speed To make the software easier to understand Write for people, not the compiler Understand unfamiliar code To help find bugs refactor while debugging to clarify the code To “Fix broken windows” - Pragmatic Programmers Licensed Under Creative Commons by Naresh Jain 9
  10. 10. Readability Which code segment is easier to read? Sample 1 if (date.before(Summer_Start) || date.after(Summer_End)){ charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; } Sample 2 if (isSummer(date)) { charge = summerCharge(quantity); Else charge = winterCharge(quantity); } Licensed Under Creative Commons by Naresh Jain 10
  11. 11. When should you refactor? To add new functionality refactor existing code until you understand it Like championship refactor the design to make it simple to add To find bugs snooker players we are setting ourselves up for refactor to understand the code For code reviews our next shot immediate effect of code review allows for higher level suggestions Licensed Under Creative Commons by Naresh Jain 11
  12. 12. The Two Hats Adding Function Refactoring Add new capabilities to the system Does not add any new features Does not add tests (but may change Adds new tests some) Get the test working Restructure the code to remove redundancy Swap frequently between the hats, but only wear one at a time Licensed Under Creative Commons by Naresh Jain 12
  13. 13. Refactoring and TDD Add a Test Pass Run the Test Fail TDD Rhythm - Test, Code, Refactor Make a little change Fail Run the Test Pass Refactor Licensed Under Creative Commons by Naresh Jain 13
  14. 14. Team Techniques Encourage refactoring culture nobody gets things right first time nobody can write clear code without reviews refactoring is forward progress Licensed Under Creative Commons by Naresh Jain 14
  15. 15. Team Techniques... Provide sound testing base tests are essential for refactoring build system and run tests daily Pair Programming two programmers working together can be quicker than working separately refactor with the class writer and a class user Licensed Under Creative Commons by Naresh Jain 15
  16. 16. How do we Refactor? We looks for Code-Smells Things that we suspect are not quite right or will cause us severe pain if we do not fix Licensed Under Creative Commons by Naresh Jain 16
  17. 17. Common Code Smells The Big Stinkers Duplicated code Long Method Feature Envy Long Parameter List Inappropriate Intimacy Switch Statements Comments Improper Naming Licensed Under Creative Commons by Naresh Jain 17
  18. 18. Duplicated Code There is obvious duplication Such as copy and paste There are unobvious duplications Such as parallel inheritance hierarchies. Similar algorithms Remedies Extract Method Pull Up Field Licensed Under Creative Commons by Naresh Jain 18
  19. 19. Feature Envy A method that seems more interested in some other class than the one it is in. Remedies: Move Method Extract Method Licensed Under Creative Commons by Naresh Jain 19
  20. 20. Extract Method void printOwning(double amount){ printBanner(); // print details System.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); } Licensed Under Creative Commons by Naresh Jain 20
  21. 21. Inappropriate Intimacy Two or more classes fiddling with each other’s private parts. Remedies Move Method and Move Field Change Bi-directional Association to Unidirectional Extract Class Licensed Under Creative Commons by Naresh Jain 21
  22. 22. Extract Class Person Person TelephoneNumber name officeAreaCode name areaCode officeNumber telephoneNumber number getTelephoneNumber getTelephoneNumber getTelephoneNumber Licensed Under Creative Commons by Naresh Jain 22
  23. 23. Comments Comments – be suspicious! Comments are a deodorant. Comments represent a failure to express an idea in the code. Remedies: Extract Method Rename Method Introduce Assertion Licensed Under Creative Commons by Naresh Jain 23
  24. 24. Introduce Assertion double GetExpenseLimit() { // should have either expense limit or a primary project return(_expenseLimit != NULL_EXPENSE) ? _expenseLimit : _primaryProject.GetMemberExpenseLimit(); } double GetExpenseLimit() { assert(_expenseLimit != NULL_EXPENSE || _primaryProject != null, “Expense Limit and Primary Project must not be null”); return(_expenseLimit != NULL_EXPENSE) ? _expenseLimit : _primaryProject.GetMemberExpenseLimit(); } Licensed Under Creative Commons by Naresh Jain 24
  25. 25. Long Method Good OO code is easiest to understand and maintain with shorter methods with good names Long methods tend to be harder to read and understand Remedies: Extract Method Replace Temp with Query Replace Method with Method Object. Decompose Conditional Licensed Under Creative Commons by Naresh Jain 25
  26. 26. Replace Temp with Query double basePrice = _quanity * if(getBasePrice() > 1000) { _itemPrice; return getBasePrice() * 0.95; if(basePrice > 1000) } { else { return basePrice * 0.95; return getBasePrice() * 0.98; } } else { double getBasePrice() { return basePrice * 0.98; return _quanitiy * _itemPrice; } } Licensed Under Creative Commons by Naresh Jain 26
  27. 27. Long parameter list Functions should have as few parameters as possible. Remedies: Replace Parameter with Method Preserve Whole Object Introduce Parameter Object Licensed Under Creative Commons by Naresh Jain 27
  28. 28. Introduce Parameter Object Customer AmoutInvoicedIn(Date start, Date end) AmoutRecivedIn(Date start, Date end) AmoutOverdueIn(Date start, Date end) Customer AmoutInvoicedIn(DateRange range) AmoutRecivedIn(DateRange range) AmoutOverdueIn(DateRange range) Licensed Under Creative Commons by Naresh Jain 28
  29. 29. Switch Statements Type cases are evil because they tend to be duplicated many times. Remedies: Replace Type Code with Subclasses Replace Type Code with State / Strategy Replace Conditional with Polymorphism. Replace Parameter with Explicit Methods Introduce Null Object. Licensed Under Creative Commons by Naresh Jain 29
  30. 30. Replace Parameter with Explicit Methods void SetValue(String name, int value) void SetHeight(int value) { { if(name.Equals(“height”)) _height = value; { } _height = value; return; } void SetWidth(int value) if(name.Equals(“width”)) { { _width = value; _width = value; } return; } Trace.Assert(false, “Should never reach here”); } Licensed Under Creative Commons by Naresh Jain 30
  31. 31. Inappropriate Naming Names given to variables (fields) and methods should be clear and meaningful. A variable name should say exactly what it is. Which is better? private string s; OR private string salary; A method should say exactly what it does. Which is better? public double calc (double s) public double calculateFederalTaxes (double salary) Licensed Under Creative Commons by Naresh Jain 31
  32. 32. Refactoring & Patterns There is a natural relation between patterns and refactorings. Patterns are where you want to be; refactorings are ways to get there from somewhere else. - Martin Fowler Licensed Under Creative Commons by Naresh Jain 32
  33. 33. Refactoring to Patterns Creation – creation of objects Simplification – code simplification Generalization – code abstraction Protection – improve protection of existing code Accumulation – information accumulation code Utilities – misc Licensed Under Creative Commons by Naresh Jain 33
  34. 34. How to refactor Legacy Code? Identify change points Find an inflection point Cover the inflection point Break external dependencies Break internal dependencies Write tests Make changes Refactor the covered code. Licensed Under Creative Commons by Naresh Jain 34
  35. 35. Essential Reading Licensed Under Creative Commons by Naresh Jain 35
  36. 36. Refactoring Hands-on We’ll use an open source project to apply refactoring lessons Make sure your laptops are setup with the project Form pairs and each pair picks up a module/package of the open source project. Licensed Under Creative Commons by Naresh Jain 36
  37. 37. Refactoring Hands-on... You will be introduced to 2-3 code smells at a time Apply lessons form working with legacy code to write tests around your inflection point Apply lessons from refactoring and refactoring to patterns to eradicate the code smells Repeat last 3 steps, till we run out of time Licensed Under Creative Commons by Naresh Jain 37
  38. 38. Thank you Java Refactoring Fest Naresh Jain naresh@agilefaqs.com Licensed Under Creative Commons by Naresh Jain 38
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×