SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
Java
Refactoring Fest
          Naresh Jain
     naresh@agilefaqs.com



  Licensed Under Creative Commons by Naresh Jain
                                                   1
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
Three Golden Rules


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




                  Licensed Under Creative Commons by Naresh Jain
                                                                   3
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Extract Class

      Person                           Person                  TelephoneNumber
name
officeAreaCode                     name                        areaCode
officeNumber                       telephoneNumber             number

getTelephoneNumber                 getTelephoneNumber          getTelephoneNumber




                     Licensed Under Creative Commons by Naresh Jain
                                                                                    22
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
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
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
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
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
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
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
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
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
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
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
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
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 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
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
Thank you
    Java Refactoring Fest

        Naresh Jain
   naresh@agilefaqs.com


Licensed Under Creative Commons by Naresh Jain
                                                 38

Mais conteúdo relacionado

Mais procurados

Agile Maintenance
Agile MaintenanceAgile Maintenance
Agile MaintenanceNaresh Jain
 
XP And Scrum Practices
XP And Scrum PracticesXP And Scrum Practices
XP And Scrum PracticesNaresh Jain
 
Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)
Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)
Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)Directi Group
 
11 best practices_for_peer_code_review
11 best practices_for_peer_code_review11 best practices_for_peer_code_review
11 best practices_for_peer_code_reviewSmartBear Software
 
Managing Iterations
Managing IterationsManaging Iterations
Managing IterationsNaresh Jain
 
D.mathieson agile software_development_using_scrum
D.mathieson agile software_development_using_scrumD.mathieson agile software_development_using_scrum
D.mathieson agile software_development_using_scrumRamkumar Sundarakalatharan
 
How does pair programming work?
How does pair programming work?How does pair programming work?
How does pair programming work?Ferdous Pathan
 
Agile Software Development Process Practice in Thai Culture
Agile Software Development Process Practice in Thai CultureAgile Software Development Process Practice in Thai Culture
Agile Software Development Process Practice in Thai CultureWee Witthawaskul
 
Agile Software Development in Practice - A Developer Perspective
Agile Software Development in Practice - A Developer PerspectiveAgile Software Development in Practice - A Developer Perspective
Agile Software Development in Practice - A Developer PerspectiveWee Witthawaskul
 
Essential Elements Of Distributed Agile
Essential Elements Of Distributed AgileEssential Elements Of Distributed Agile
Essential Elements Of Distributed AgileVernon Stinebaker
 
Agile Software Design
Agile Software DesignAgile Software Design
Agile Software Designeduardomg23
 
Software testing agile_environment_wp
Software testing agile_environment_wpSoftware testing agile_environment_wp
Software testing agile_environment_wpCristiano Caetano
 
Agile tour 2011 ralph jocham - scrum primer
Agile tour 2011   ralph jocham - scrum primerAgile tour 2011   ralph jocham - scrum primer
Agile tour 2011 ralph jocham - scrum primerAgora Group
 
Ralph jocham agile portfolio based release trains
Ralph jocham agile portfolio based release trainsRalph jocham agile portfolio based release trains
Ralph jocham agile portfolio based release trainsAgora Group
 
Behavior Driven Development (BDD)
Behavior Driven Development (BDD)Behavior Driven Development (BDD)
Behavior Driven Development (BDD)Ajay Danait
 
Чингис Санданов - Что такое DevOps (What is DevOps)
Чингис Санданов - Что такое DevOps (What is DevOps)Чингис Санданов - Что такое DevOps (What is DevOps)
Чингис Санданов - Что такое DevOps (What is DevOps)DrupalSib
 

Mais procurados (20)

Agile Maintenance
Agile MaintenanceAgile Maintenance
Agile Maintenance
 
XP And Scrum Practices
XP And Scrum PracticesXP And Scrum Practices
XP And Scrum Practices
 
Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)
Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)
Our Journey Down the Yellow Brick Road (Agile Adoption @ Directi)
 
11 best practices_for_peer_code_review
11 best practices_for_peer_code_review11 best practices_for_peer_code_review
11 best practices_for_peer_code_review
 
Managing Iterations
Managing IterationsManaging Iterations
Managing Iterations
 
D.mathieson agile software_development_using_scrum
D.mathieson agile software_development_using_scrumD.mathieson agile software_development_using_scrum
D.mathieson agile software_development_using_scrum
 
Creating value using Agile Methods- Nanda Lankalapalli
Creating value using Agile Methods- Nanda LankalapalliCreating value using Agile Methods- Nanda Lankalapalli
Creating value using Agile Methods- Nanda Lankalapalli
 
How does pair programming work?
How does pair programming work?How does pair programming work?
How does pair programming work?
 
Agile Software Development Process Practice in Thai Culture
Agile Software Development Process Practice in Thai CultureAgile Software Development Process Practice in Thai Culture
Agile Software Development Process Practice in Thai Culture
 
Agile Software Development in Practice - A Developer Perspective
Agile Software Development in Practice - A Developer PerspectiveAgile Software Development in Practice - A Developer Perspective
Agile Software Development in Practice - A Developer Perspective
 
Essential Elements Of Distributed Agile
Essential Elements Of Distributed AgileEssential Elements Of Distributed Agile
Essential Elements Of Distributed Agile
 
Agile Software Design
Agile Software DesignAgile Software Design
Agile Software Design
 
Software testing agile_environment_wp
Software testing agile_environment_wpSoftware testing agile_environment_wp
Software testing agile_environment_wp
 
Cu32604607
Cu32604607Cu32604607
Cu32604607
 
Agile tour 2011 ralph jocham - scrum primer
Agile tour 2011   ralph jocham - scrum primerAgile tour 2011   ralph jocham - scrum primer
Agile tour 2011 ralph jocham - scrum primer
 
Ralph jocham agile portfolio based release trains
Ralph jocham agile portfolio based release trainsRalph jocham agile portfolio based release trains
Ralph jocham agile portfolio based release trains
 
Whipp q3 2008_sv
Whipp q3 2008_svWhipp q3 2008_sv
Whipp q3 2008_sv
 
Behavior Driven Development (BDD)
Behavior Driven Development (BDD)Behavior Driven Development (BDD)
Behavior Driven Development (BDD)
 
Чингис Санданов - Что такое DevOps (What is DevOps)
Чингис Санданов - Что такое DevOps (What is DevOps)Чингис Санданов - Что такое DevOps (What is DevOps)
Чингис Санданов - Что такое DevOps (What is DevOps)
 
MVP Hacks
MVP HacksMVP Hacks
MVP Hacks
 

Destaque

The Limited Red Society
The Limited Red SocietyThe Limited Red Society
The Limited Red SocietyNaresh Jain
 
ATDD - Acceptance Test Driven Development
ATDD - Acceptance Test Driven DevelopmentATDD - Acceptance Test Driven Development
ATDD - Acceptance Test Driven DevelopmentNaresh Jain
 
Software Development The Trekkers Way
Software Development The Trekkers WaySoftware Development The Trekkers Way
Software Development The Trekkers WayNaresh Jain
 
Continuous Deployment Demystified
Continuous Deployment DemystifiedContinuous Deployment Demystified
Continuous Deployment DemystifiedNaresh Jain
 
Value Driven Development by Dave Thomas
Value Driven Development by Dave Thomas Value Driven Development by Dave Thomas
Value Driven Development by Dave Thomas Naresh Jain
 
Towards FutureOps: Stable, Repeatable environments from Dev to Prod
Towards FutureOps: Stable, Repeatable environments from Dev to ProdTowards FutureOps: Stable, Repeatable environments from Dev to Prod
Towards FutureOps: Stable, Repeatable environments from Dev to ProdNaresh Jain
 
Agile India 2017 Conference
Agile India 2017 ConferenceAgile India 2017 Conference
Agile India 2017 ConferenceNaresh Jain
 
Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)wolframkriesing
 
ScrumBan Evolution - What is you next step?
ScrumBan Evolution - What is you next step?ScrumBan Evolution - What is you next step?
ScrumBan Evolution - What is you next step?Sebastian Radics
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefAhmed Shreef
 

Destaque (14)

The Limited Red Society
The Limited Red SocietyThe Limited Red Society
The Limited Red Society
 
ATDD - Acceptance Test Driven Development
ATDD - Acceptance Test Driven DevelopmentATDD - Acceptance Test Driven Development
ATDD - Acceptance Test Driven Development
 
TDD Overview
TDD OverviewTDD Overview
TDD Overview
 
Software Development The Trekkers Way
Software Development The Trekkers WaySoftware Development The Trekkers Way
Software Development The Trekkers Way
 
Continuous Deployment Demystified
Continuous Deployment DemystifiedContinuous Deployment Demystified
Continuous Deployment Demystified
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
 
Value Driven Development by Dave Thomas
Value Driven Development by Dave Thomas Value Driven Development by Dave Thomas
Value Driven Development by Dave Thomas
 
Towards FutureOps: Stable, Repeatable environments from Dev to Prod
Towards FutureOps: Stable, Repeatable environments from Dev to ProdTowards FutureOps: Stable, Repeatable environments from Dev to Prod
Towards FutureOps: Stable, Repeatable environments from Dev to Prod
 
Agile India 2017 Conference
Agile India 2017 ConferenceAgile India 2017 Conference
Agile India 2017 Conference
 
Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)
 
Tdd
TddTdd
Tdd
 
Bad Smell In Codes 1
Bad Smell In Codes 1Bad Smell In Codes 1
Bad Smell In Codes 1
 
ScrumBan Evolution - What is you next step?
ScrumBan Evolution - What is you next step?ScrumBan Evolution - What is you next step?
ScrumBan Evolution - What is you next step?
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 

Semelhante a Refactoring Fest

Introduction to Extreme Programming
Introduction to Extreme ProgrammingIntroduction to Extreme Programming
Introduction to Extreme ProgrammingNaresh Jain
 
xTreme Programming by Sejo Ćesić and Enis Zeherović
xTreme Programming by Sejo Ćesić and Enis ZeherovićxTreme Programming by Sejo Ćesić and Enis Zeherović
xTreme Programming by Sejo Ćesić and Enis ZeherovićBosnia Agile
 
Releasing fast code - The DevOps approach
Releasing fast code - The DevOps approachReleasing fast code - The DevOps approach
Releasing fast code - The DevOps approachMichael Kopp
 
Waterfallacies V1 1
Waterfallacies V1 1Waterfallacies V1 1
Waterfallacies V1 1Jorge Boria
 
The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)Stefan Koopmanschap
 
The Power Of Refactoring (PHPCon Italia)
The Power Of Refactoring (PHPCon Italia)The Power Of Refactoring (PHPCon Italia)
The Power Of Refactoring (PHPCon Italia)Stefan Koopmanschap
 
Devnology back toschool software reengineering
Devnology back toschool software reengineeringDevnology back toschool software reengineering
Devnology back toschool software reengineeringDevnology
 
The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)Stefan Koopmanschap
 
Analysis of the interaction between practices for introducing XP effectively
Analysis of the interaction between practices for introducing XP effectivelyAnalysis of the interaction between practices for introducing XP effectively
Analysis of the interaction between practices for introducing XP effectivelyMakoto SAKAI
 
Test driven development and react js application go hand in hand
Test driven development and react js application go hand in handTest driven development and react js application go hand in hand
Test driven development and react js application go hand in handKaty Slemon
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in RefactoringChamnap Chhorn
 
Tester developer interaction
Tester developer interactionTester developer interaction
Tester developer interactiongaoliang641
 
How to Profit from Static Analysis
How to Profit from Static AnalysisHow to Profit from Static Analysis
How to Profit from Static AnalysisElena Laskavaia
 
Agile Values, Principles and Practices
Agile Values, Principles and PracticesAgile Values, Principles and Practices
Agile Values, Principles and Practicesjackcrews
 

Semelhante a Refactoring Fest (20)

Introduction to Extreme Programming
Introduction to Extreme ProgrammingIntroduction to Extreme Programming
Introduction to Extreme Programming
 
xTreme Programming by Sejo Ćesić and Enis Zeherović
xTreme Programming by Sejo Ćesić and Enis ZeherovićxTreme Programming by Sejo Ćesić and Enis Zeherović
xTreme Programming by Sejo Ćesić and Enis Zeherović
 
Releasing fast code - The DevOps approach
Releasing fast code - The DevOps approachReleasing fast code - The DevOps approach
Releasing fast code - The DevOps approach
 
Testing and symfony2
Testing and symfony2Testing and symfony2
Testing and symfony2
 
Refactoring 2 The Max
Refactoring 2 The MaxRefactoring 2 The Max
Refactoring 2 The Max
 
Waterfallacies V1 1
Waterfallacies V1 1Waterfallacies V1 1
Waterfallacies V1 1
 
Refactoring
RefactoringRefactoring
Refactoring
 
The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)The Power Of Refactoring (4developers Krakow)
The Power Of Refactoring (4developers Krakow)
 
The Power Of Refactoring (PHPCon Italia)
The Power Of Refactoring (PHPCon Italia)The Power Of Refactoring (PHPCon Italia)
The Power Of Refactoring (PHPCon Italia)
 
TDD (with FLOW3)
TDD (with FLOW3)TDD (with FLOW3)
TDD (with FLOW3)
 
Devnology back toschool software reengineering
Devnology back toschool software reengineeringDevnology back toschool software reengineering
Devnology back toschool software reengineering
 
The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)The Power Of Refactoring (php|tek 09)
The Power Of Refactoring (php|tek 09)
 
Reduce Reuse Refactor
Reduce Reuse RefactorReduce Reuse Refactor
Reduce Reuse Refactor
 
Analysis of the interaction between practices for introducing XP effectively
Analysis of the interaction between practices for introducing XP effectivelyAnalysis of the interaction between practices for introducing XP effectively
Analysis of the interaction between practices for introducing XP effectively
 
Test driven development and react js application go hand in hand
Test driven development and react js application go hand in handTest driven development and react js application go hand in hand
Test driven development and react js application go hand in hand
 
Introduction to refactoring
Introduction to refactoringIntroduction to refactoring
Introduction to refactoring
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in Refactoring
 
Tester developer interaction
Tester developer interactionTester developer interaction
Tester developer interaction
 
How to Profit from Static Analysis
How to Profit from Static AnalysisHow to Profit from Static Analysis
How to Profit from Static Analysis
 
Agile Values, Principles and Practices
Agile Values, Principles and PracticesAgile Values, Principles and Practices
Agile Values, Principles and Practices
 

Mais de Naresh Jain

Problem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary DesignProblem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary DesignNaresh Jain
 
Agile India 2019 Conference Welcome Note
Agile India 2019 Conference Welcome NoteAgile India 2019 Conference Welcome Note
Agile India 2019 Conference Welcome NoteNaresh Jain
 
Organizational Resilience
Organizational ResilienceOrganizational Resilience
Organizational ResilienceNaresh Jain
 
Improving the Quality of Incoming Code
Improving the Quality of Incoming CodeImproving the Quality of Incoming Code
Improving the Quality of Incoming CodeNaresh Jain
 
Agile India 2018 Conference Summary
Agile India 2018 Conference SummaryAgile India 2018 Conference Summary
Agile India 2018 Conference SummaryNaresh Jain
 
Agile India 2018 Conference
Agile India 2018 ConferenceAgile India 2018 Conference
Agile India 2018 ConferenceNaresh Jain
 
Agile India 2018 Conference
Agile India 2018 ConferenceAgile India 2018 Conference
Agile India 2018 ConferenceNaresh Jain
 
Agile India 2018 Conference
Agile India 2018 ConferenceAgile India 2018 Conference
Agile India 2018 ConferenceNaresh Jain
 
Pilgrim's Progress to the Promised Land by Robert Virding
Pilgrim's Progress to the Promised Land by Robert VirdingPilgrim's Progress to the Promised Land by Robert Virding
Pilgrim's Progress to the Promised Land by Robert VirdingNaresh Jain
 
Concurrent languages are Functional by Francesco Cesarini
Concurrent languages are Functional by Francesco CesariniConcurrent languages are Functional by Francesco Cesarini
Concurrent languages are Functional by Francesco CesariniNaresh Jain
 
Erlang from behing the trenches by Francesco Cesarini
Erlang from behing the trenches by Francesco CesariniErlang from behing the trenches by Francesco Cesarini
Erlang from behing the trenches by Francesco CesariniNaresh Jain
 
Anatomy of an eCommerce Search Engine by Mayur Datar
Anatomy of an eCommerce Search Engine by Mayur DatarAnatomy of an eCommerce Search Engine by Mayur Datar
Anatomy of an eCommerce Search Engine by Mayur DatarNaresh Jain
 
Setting up Continuous Delivery Culture for a Large Scale Mobile App
Setting up Continuous Delivery Culture for a Large Scale Mobile AppSetting up Continuous Delivery Culture for a Large Scale Mobile App
Setting up Continuous Delivery Culture for a Large Scale Mobile AppNaresh Jain
 
No Silver Bullets in Functional Programming by Brian McKenna
No Silver Bullets in Functional Programming by Brian McKennaNo Silver Bullets in Functional Programming by Brian McKenna
No Silver Bullets in Functional Programming by Brian McKennaNaresh Jain
 
Functional Programming Conference 2016
Functional Programming Conference 2016Functional Programming Conference 2016
Functional Programming Conference 2016Naresh Jain
 
Unleashing the Power of Automated Refactoring with JDT
Unleashing the Power of Automated Refactoring with JDTUnleashing the Power of Automated Refactoring with JDT
Unleashing the Power of Automated Refactoring with JDTNaresh Jain
 
Getting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo Kim
Getting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo KimGetting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo Kim
Getting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo KimNaresh Jain
 
MVP Design Hacks
MVP Design HacksMVP Design Hacks
MVP Design HacksNaresh Jain
 
Functional Conf 2015
Functional Conf 2015Functional Conf 2015
Functional Conf 2015Naresh Jain
 

Mais de Naresh Jain (20)

Problem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary DesignProblem Solving Techniques For Evolutionary Design
Problem Solving Techniques For Evolutionary Design
 
Agile India 2019 Conference Welcome Note
Agile India 2019 Conference Welcome NoteAgile India 2019 Conference Welcome Note
Agile India 2019 Conference Welcome Note
 
Organizational Resilience
Organizational ResilienceOrganizational Resilience
Organizational Resilience
 
Improving the Quality of Incoming Code
Improving the Quality of Incoming CodeImproving the Quality of Incoming Code
Improving the Quality of Incoming Code
 
Agile India 2018 Conference Summary
Agile India 2018 Conference SummaryAgile India 2018 Conference Summary
Agile India 2018 Conference Summary
 
Agile India 2018 Conference
Agile India 2018 ConferenceAgile India 2018 Conference
Agile India 2018 Conference
 
Agile India 2018 Conference
Agile India 2018 ConferenceAgile India 2018 Conference
Agile India 2018 Conference
 
Agile India 2018 Conference
Agile India 2018 ConferenceAgile India 2018 Conference
Agile India 2018 Conference
 
Pilgrim's Progress to the Promised Land by Robert Virding
Pilgrim's Progress to the Promised Land by Robert VirdingPilgrim's Progress to the Promised Land by Robert Virding
Pilgrim's Progress to the Promised Land by Robert Virding
 
Concurrent languages are Functional by Francesco Cesarini
Concurrent languages are Functional by Francesco CesariniConcurrent languages are Functional by Francesco Cesarini
Concurrent languages are Functional by Francesco Cesarini
 
Erlang from behing the trenches by Francesco Cesarini
Erlang from behing the trenches by Francesco CesariniErlang from behing the trenches by Francesco Cesarini
Erlang from behing the trenches by Francesco Cesarini
 
Anatomy of an eCommerce Search Engine by Mayur Datar
Anatomy of an eCommerce Search Engine by Mayur DatarAnatomy of an eCommerce Search Engine by Mayur Datar
Anatomy of an eCommerce Search Engine by Mayur Datar
 
Setting up Continuous Delivery Culture for a Large Scale Mobile App
Setting up Continuous Delivery Culture for a Large Scale Mobile AppSetting up Continuous Delivery Culture for a Large Scale Mobile App
Setting up Continuous Delivery Culture for a Large Scale Mobile App
 
No Silver Bullets in Functional Programming by Brian McKenna
No Silver Bullets in Functional Programming by Brian McKennaNo Silver Bullets in Functional Programming by Brian McKenna
No Silver Bullets in Functional Programming by Brian McKenna
 
Functional Programming Conference 2016
Functional Programming Conference 2016Functional Programming Conference 2016
Functional Programming Conference 2016
 
The Eclipse Way
The Eclipse WayThe Eclipse Way
The Eclipse Way
 
Unleashing the Power of Automated Refactoring with JDT
Unleashing the Power of Automated Refactoring with JDTUnleashing the Power of Automated Refactoring with JDT
Unleashing the Power of Automated Refactoring with JDT
 
Getting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo Kim
Getting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo KimGetting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo Kim
Getting2Alpha: Turbo-charge your product with Game Thinking by Amy Jo Kim
 
MVP Design Hacks
MVP Design HacksMVP Design Hacks
MVP Design Hacks
 
Functional Conf 2015
Functional Conf 2015Functional Conf 2015
Functional Conf 2015
 

Último

Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 

Último (20)

Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 

Refactoring Fest

  • 1. Java Refactoring Fest Naresh Jain naresh@agilefaqs.com Licensed Under Creative Commons by Naresh Jain 1
  • 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. Three Golden Rules Once and only once [DRY] Express intent Tell, don’t ask Licensed Under Creative Commons by Naresh Jain 3
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Extract Class Person Person TelephoneNumber name officeAreaCode name areaCode officeNumber telephoneNumber number getTelephoneNumber getTelephoneNumber getTelephoneNumber Licensed Under Creative Commons by Naresh Jain 22
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Essential Reading Licensed Under Creative Commons by Naresh Jain 35
  • 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. 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. Thank you Java Refactoring Fest Naresh Jain naresh@agilefaqs.com Licensed Under Creative Commons by Naresh Jain 38