SlideShare a Scribd company logo
1 of 26
CODE REFACTORING



           Phạm Anh Đới – doipa@fpt.com.vn
      Nguyễn Việt Khoa – khoanv4@fpt.com.vn
                              Hanoi, 11/2011
Code Refactoring – TechTalks #6   2




Objectives
 •     What’s Code Refactoring?

 •     Why do we Refactor?

 •     When should we Refactor?

 •     How do we Refactor?

 •     Refactoring Techniques

 •     Code Refactoring Tools

 •     Refactoring Dojo
Code Refactoring – TechTalks #6                3




What’s Code Refactoring?

 “A series of small steps, each of which changes
 the program’s internalstructure without
 changing its external behavior “
                                   Martin Fowler
Code Refactoring – TechTalks #6               4




What’s Code Refactoring?
• Code reorganization
   o Implies equivalence
   o Change the structure, not the behavior
• Cleans up “code-smell”
• Does NOT fix bugs
Code Refactoring – TechTalks #6                    5




Why do we Refactor?
•    Helps us deliver more business value faster
•    Improves the design of our software
•    Minimizes technical debt
•    Keep development at speed
•    To make the software easier to understand
•    To help find bugs
•    To “Fix broken windows”
Code Refactoring – TechTalks #6                             6




Example
Which code segment is easier to read?

 Sample 1:
 if (markT>=0 && markT<=25 && markL>=0 && markL<=25){
             float markAvg = (markT + markL)/2;
             System.out.println("Your mark: " + markAvg);
 }

 Sample 2:
 if (isValid(markT) && isValid(markL)){
             float markAvg = (markT + markL)/2;
             System.out.println("Your mark: " + mark);
 }
Code Refactoring – TechTalks #6                        7




When should we Refactor?
   • To add new functionality
    o refactor existing code until you understand it
    o refactor the design to make it simple to add
   • To find bugs
    o refactor to understand the code
   • For code reviews
    o immediate effect of code review
    o allows for higher level suggestions
Code Refactoring – TechTalks #6                                 8




How do we Refactor?
• Manual Refactoring
   o Code Smells
• Automated/Assisted Refactoring
   o Refactoring by hand is time consuming and prone to error
   o Tools (IDE)
• In either case, test your changes
Code Refactoring – TechTalks #6                           9




Code Smell
•Duplicated code                  • Long Method

• Feature Envy                    • Long Parameter List

• Inappropriate Intimacy          • Switch Statements

• Comments                        • Improper Naming
Code Refactoring – TechTalks #6                10




Code Smell examples (1)
public void display(String[] names) {
   System.out.println(“--------------");
   for(int i=0; i<names.length; i++){
       System.out.println(“ + " + names[i]);
   }
   System.out.println(“--------------");
}
                             Duplicated code
public void listMember(String[] names) {
   System.out.println(“List all member: ”);
   System.out.println(“--------------");
   for(int i=0; i<names.length; i++){
       System.out.println(“ + " + names[i]);
   }
   System.out.println(“--------------");
}
Code Refactoring – TechTalks #6                      11




Code Smell examples (2)
      public int getSum() {
           Scanner input = new Scanner(System.in);
           int[] list = new int[100];
           //Input
           System.out.println("count:");
           int count= input.nextInt();
           for (int i= 0; i < count; i++) {
                                  Long Method
               list[i] = input.nextInt();
           }

              //Get sum
              int sum=0;
              for (int i= 0; i < count; i++) {
                  sum+=list[i];
              }
              return sum;
       }
Code Refactoring – TechTalks #6             12




Code Smell examples (3)
public String formatStudent( int id,
                         String name,
                         Date dob,
                         String province,
                         String address,
           Long Parameter List
                         String phone ){
  //TODO:
  return null;
}
Code Refactoring – TechTalks #6   13




Refactoring Techniques

• for more abstraction

• for breaking code apart

• for improving code standard
Code Refactoring – TechTalks #6                  14




For more abstraction
• Encapsulate Field – force code to access the
      field with getter and setter methods
• Generalize Type – create more general types to
      allow for more code sharing
• Replace type-checking code with State/Strategy
• Replace conditional with polymorphism
Code Refactoring – TechTalks #6                                      15



Example
public class Book{
    private String title;
public class Book{
   String title;
   public void setTitle(String title){
        if(title!=null){
    public title = void main(String[] args) {
           static title.trim();
           if(!title.isEmpty()){
       Book book = new Book();
               this.title = title;
           }
       String title = new Scanner(System.in).nextLine();
       }
    }  if(title!=null){
                 title = title.trim();
    public String getTitle(){
             if(!title.isEmpty()){
        return title;
    }           book.title = title;
                      System.out.println("My book: " + book.title);
  public static void main(String[] args) {
           }
      Book book = new Book();
      }
      String title = new Scanner(System.in).nextLine();
  } book.setTitle(title);
}     System.out.println("My book: " + book.getTitle());
  }
}
Code Refactoring – TechTalks #6                      16




For breaking code apart
• Extract Method, to turn part of a larger method
      into a new method. By breaking down code in
      smaller pieces, it is more easily understandable.
      This is also applicable to functions.
•     Extract Class moves part of the code from an
      existing class into a new class.
Code Refactoring – TechTalks #6                    17




Example
public void showInfor(){
     showUser();
       showUser();

     System.out.println(“Email: “ +
       showContact();                 email);
}    System.out.println(“Phone: “ +   phone);
     System.out.println(“Address: “   + address);
public void showContact(){
}
     System.out.println(“Email: “ +   email);
     System.out.println(“Phone: “ +   phone);
     System.out.println(“Address: “   + address);
}
Code Refactoring – TechTalks #6                        18




For improving code standard
• Move Method or Move Field – move to a more
  appropriate Class or source file
• Rename Method or Rename Field – changing
     the name into a new one that better reveals its
     purpose
• Pull Up – in OOP, move to a superclass
• Push Down – in OOP, move to a subclass
Code Refactoring – TechTalks #6   19




Example
Code Refactoring – TechTalks #6                      20




Tools for Code Refactoring
   Supported by IDE
    • For Java:
        o Netbeans (www.netbeans.org)
        o Eclipse (www.eclipse.org)
        o IntelliJ IDEA (www.jetbrains.com)
     • For .NET:
        o Visual Studio (msdn.microsoft.com)
        o .NET Refactoring (www.dotnetrefactoring.com)
        o JustCode, ReSharper, Visual Assist, …
              (addon for Visual Studio)
Code Refactoring – TechTalks #6   21




Refactoring Dojo
Code Refactoring – TechTalks #6                       22




Refactoring and TDD




                  TDD Rhythm - Test, Code, Refactor
Code Refactoring – TechTalks #6                            23




Summary
• Improving the design of existing code
• Refactoring does not affect behavior
• The system is also kept fully working after each small
     refactoring
•    Two general categories of benefits to the activity of
     refactoring: Maintainability and Extensibility
•    3 techniques for refactoring
•    Using tools for Code Refactoring
•    Code Refactoring are often used to improve quality and
     enhance project agility.
Code Refactoring – TechTalks #6   24




Q&A
Code Refactoring – TechTalks #6                 25




References
•Book: Improving the Design of Existing
  Code (by Martin Fowler)
•Sites:
   • http://refactoring.com
   • http://en.wikipedia.org/wiki/Refactoring
   • http://wiki.netbeans.org/Refactoring
   • http://msdn.microsoft.com/en-
     us/library/ms379618(v=vs.80).aspx
Code Refactoring – TechTalks #6                                   26




                      Thank you
                          doipa@fpt.com.vn – khoanv4@fpt.com.vn

More Related Content

What's hot

Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smellsPaul Nguyen
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowRachid Kherrazi
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleMarian Wamsiedel
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Codeslicklash
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based TestingSumant Tambe
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven DevelopmentTung Nguyen Thanh
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 

What's hot (20)

Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Refactoring
RefactoringRefactoring
Refactoring
 
Refactoring
RefactoringRefactoring
Refactoring
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlow
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical example
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Code Smells
Code SmellsCode Smells
Code Smells
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based Testing
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 

Viewers also liked

Agile estimation & planning
Agile estimation & planningAgile estimation & planning
Agile estimation & planningDUONG Trong Tan
 
TMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and ReportsTMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and ReportsMichel Alves
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Peter Kofler
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command LineBrian Richards
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modulestanoshimi
 
FLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactFLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactMichel Alves
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises Michel Alves
 
Manipulating file in Python
Manipulating file in PythonManipulating file in Python
Manipulating file in Pythonshoukatali500
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Anil Sagar
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactMichel Alves
 
FLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactFLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactMichel Alves
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh ImpactMichel Alves
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development processPolished Geek LLC
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP DevelopersUmut IŞIK
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...Alessandro Molina
 
FLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesFLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesMichel Alves
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsCarl Brown
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con PythonManuel Pérez
 

Viewers also liked (20)

ScrumLab
ScrumLabScrumLab
ScrumLab
 
Agile estimation & planning
Agile estimation & planningAgile estimation & planning
Agile estimation & planning
 
TMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and ReportsTMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and Reports
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command Line
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modules
 
FLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactFLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth Impact
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises
 
Advanced Git
Advanced GitAdvanced Git
Advanced Git
 
Manipulating file in Python
Manipulating file in PythonManipulating file in Python
Manipulating file in Python
 
Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2Blisstering drupal module development ppt v1.2
Blisstering drupal module development ppt v1.2
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second Impact
 
FLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactFLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third Impact
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh Impact
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP Developers
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
 
FLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesFLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - Exercises
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and Concepts
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con Python
 

Similar to Tech talks#6: Code Refactoring

Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019Paulo Clavijo
 
Assuring the code quality of share point solutions and apps - Matthias Einig
Assuring the code quality of share point solutions and apps - Matthias EinigAssuring the code quality of share point solutions and apps - Matthias Einig
Assuring the code quality of share point solutions and apps - Matthias EinigSPC Adriatics
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
What’s eating python performance
What’s eating python performanceWhat’s eating python performance
What’s eating python performancePiotr Przymus
 
SQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET FundamentalsSQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET Fundamentalsmikehuguet
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...Antonio de la Torre Fernández
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 
Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4Joubin Najmaie
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
refactoring code by clean code rules
refactoring code by clean code rulesrefactoring code by clean code rules
refactoring code by clean code rulessaber tabatabaee
 
Comunicare, condividere e mantenere decisioni architetturali nei team di svil...
Comunicare, condividere e mantenere decisioni architetturali nei team di svil...Comunicare, condividere e mantenere decisioni architetturali nei team di svil...
Comunicare, condividere e mantenere decisioni architetturali nei team di svil...Michele Orselli
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 

Similar to Tech talks#6: Code Refactoring (20)

Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
 
Refactoring
RefactoringRefactoring
Refactoring
 
Assuring the code quality of share point solutions and apps - Matthias Einig
Assuring the code quality of share point solutions and apps - Matthias EinigAssuring the code quality of share point solutions and apps - Matthias Einig
Assuring the code quality of share point solutions and apps - Matthias Einig
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
What’s eating python performance
What’s eating python performanceWhat’s eating python performance
What’s eating python performance
 
SQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET FundamentalsSQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET Fundamentals
 
More about PHP
More about PHPMore about PHP
More about PHP
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 
Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Dapper
DapperDapper
Dapper
 
refactoring code by clean code rules
refactoring code by clean code rulesrefactoring code by clean code rules
refactoring code by clean code rules
 
Comunicare, condividere e mantenere decisioni architetturali nei team di svil...
Comunicare, condividere e mantenere decisioni architetturali nei team di svil...Comunicare, condividere e mantenere decisioni architetturali nei team di svil...
Comunicare, condividere e mantenere decisioni architetturali nei team di svil...
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Old code doesn't stink
Old code doesn't stinkOld code doesn't stink
Old code doesn't stink
 

More from Nguyễn Việt Khoa

More from Nguyễn Việt Khoa (7)

Giới thiệu về Coding Dojo [at]CocoDojo.hn.vn
Giới thiệu về Coding Dojo [at]CocoDojo.hn.vnGiới thiệu về Coding Dojo [at]CocoDojo.hn.vn
Giới thiệu về Coding Dojo [at]CocoDojo.hn.vn
 
Sơ lược về StAX
Sơ lược về StAXSơ lược về StAX
Sơ lược về StAX
 
[Kaizen Game] Airplance Production
[Kaizen Game] Airplance Production[Kaizen Game] Airplance Production
[Kaizen Game] Airplance Production
 
Giới thiệu ngắn về DOM
Giới thiệu ngắn về DOMGiới thiệu ngắn về DOM
Giới thiệu ngắn về DOM
 
Giới thiệu ngắn về SAX
Giới thiệu ngắn về SAXGiới thiệu ngắn về SAX
Giới thiệu ngắn về SAX
 
Giới thiệu về JAXP
Giới thiệu về JAXPGiới thiệu về JAXP
Giới thiệu về JAXP
 
FAT.Seminar.FOSS_Joomla!
FAT.Seminar.FOSS_Joomla!FAT.Seminar.FOSS_Joomla!
FAT.Seminar.FOSS_Joomla!
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Tech talks#6: Code Refactoring

  • 1. CODE REFACTORING Phạm Anh Đới – doipa@fpt.com.vn Nguyễn Việt Khoa – khoanv4@fpt.com.vn Hanoi, 11/2011
  • 2. Code Refactoring – TechTalks #6 2 Objectives • What’s Code Refactoring? • Why do we Refactor? • When should we Refactor? • How do we Refactor? • Refactoring Techniques • Code Refactoring Tools • Refactoring Dojo
  • 3. Code Refactoring – TechTalks #6 3 What’s Code Refactoring? “A series of small steps, each of which changes the program’s internalstructure without changing its external behavior “ Martin Fowler
  • 4. Code Refactoring – TechTalks #6 4 What’s Code Refactoring? • Code reorganization o Implies equivalence o Change the structure, not the behavior • Cleans up “code-smell” • Does NOT fix bugs
  • 5. Code Refactoring – TechTalks #6 5 Why do we Refactor? • Helps us deliver more business value faster • Improves the design of our software • Minimizes technical debt • Keep development at speed • To make the software easier to understand • To help find bugs • To “Fix broken windows”
  • 6. Code Refactoring – TechTalks #6 6 Example Which code segment is easier to read? Sample 1: if (markT>=0 && markT<=25 && markL>=0 && markL<=25){ float markAvg = (markT + markL)/2; System.out.println("Your mark: " + markAvg); } Sample 2: if (isValid(markT) && isValid(markL)){ float markAvg = (markT + markL)/2; System.out.println("Your mark: " + mark); }
  • 7. Code Refactoring – TechTalks #6 7 When should we Refactor? • To add new functionality o refactor existing code until you understand it o refactor the design to make it simple to add • To find bugs o refactor to understand the code • For code reviews o immediate effect of code review o allows for higher level suggestions
  • 8. Code Refactoring – TechTalks #6 8 How do we Refactor? • Manual Refactoring o Code Smells • Automated/Assisted Refactoring o Refactoring by hand is time consuming and prone to error o Tools (IDE) • In either case, test your changes
  • 9. Code Refactoring – TechTalks #6 9 Code Smell •Duplicated code • Long Method • Feature Envy • Long Parameter List • Inappropriate Intimacy • Switch Statements • Comments • Improper Naming
  • 10. Code Refactoring – TechTalks #6 10 Code Smell examples (1) public void display(String[] names) { System.out.println(“--------------"); for(int i=0; i<names.length; i++){ System.out.println(“ + " + names[i]); } System.out.println(“--------------"); } Duplicated code public void listMember(String[] names) { System.out.println(“List all member: ”); System.out.println(“--------------"); for(int i=0; i<names.length; i++){ System.out.println(“ + " + names[i]); } System.out.println(“--------------"); }
  • 11. Code Refactoring – TechTalks #6 11 Code Smell examples (2) public int getSum() { Scanner input = new Scanner(System.in); int[] list = new int[100]; //Input System.out.println("count:"); int count= input.nextInt(); for (int i= 0; i < count; i++) { Long Method list[i] = input.nextInt(); } //Get sum int sum=0; for (int i= 0; i < count; i++) { sum+=list[i]; } return sum; }
  • 12. Code Refactoring – TechTalks #6 12 Code Smell examples (3) public String formatStudent( int id, String name, Date dob, String province, String address, Long Parameter List String phone ){ //TODO: return null; }
  • 13. Code Refactoring – TechTalks #6 13 Refactoring Techniques • for more abstraction • for breaking code apart • for improving code standard
  • 14. Code Refactoring – TechTalks #6 14 For more abstraction • Encapsulate Field – force code to access the field with getter and setter methods • Generalize Type – create more general types to allow for more code sharing • Replace type-checking code with State/Strategy • Replace conditional with polymorphism
  • 15. Code Refactoring – TechTalks #6 15 Example public class Book{ private String title; public class Book{ String title; public void setTitle(String title){ if(title!=null){ public title = void main(String[] args) { static title.trim(); if(!title.isEmpty()){ Book book = new Book(); this.title = title; } String title = new Scanner(System.in).nextLine(); } } if(title!=null){ title = title.trim(); public String getTitle(){ if(!title.isEmpty()){ return title; } book.title = title; System.out.println("My book: " + book.title); public static void main(String[] args) { } Book book = new Book(); } String title = new Scanner(System.in).nextLine(); } book.setTitle(title); } System.out.println("My book: " + book.getTitle()); } }
  • 16. Code Refactoring – TechTalks #6 16 For breaking code apart • Extract Method, to turn part of a larger method into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to functions. • Extract Class moves part of the code from an existing class into a new class.
  • 17. Code Refactoring – TechTalks #6 17 Example public void showInfor(){ showUser(); showUser(); System.out.println(“Email: “ + showContact(); email); } System.out.println(“Phone: “ + phone); System.out.println(“Address: “ + address); public void showContact(){ } System.out.println(“Email: “ + email); System.out.println(“Phone: “ + phone); System.out.println(“Address: “ + address); }
  • 18. Code Refactoring – TechTalks #6 18 For improving code standard • Move Method or Move Field – move to a more appropriate Class or source file • Rename Method or Rename Field – changing the name into a new one that better reveals its purpose • Pull Up – in OOP, move to a superclass • Push Down – in OOP, move to a subclass
  • 19. Code Refactoring – TechTalks #6 19 Example
  • 20. Code Refactoring – TechTalks #6 20 Tools for Code Refactoring Supported by IDE • For Java: o Netbeans (www.netbeans.org) o Eclipse (www.eclipse.org) o IntelliJ IDEA (www.jetbrains.com) • For .NET: o Visual Studio (msdn.microsoft.com) o .NET Refactoring (www.dotnetrefactoring.com) o JustCode, ReSharper, Visual Assist, … (addon for Visual Studio)
  • 21. Code Refactoring – TechTalks #6 21 Refactoring Dojo
  • 22. Code Refactoring – TechTalks #6 22 Refactoring and TDD TDD Rhythm - Test, Code, Refactor
  • 23. Code Refactoring – TechTalks #6 23 Summary • Improving the design of existing code • Refactoring does not affect behavior • The system is also kept fully working after each small refactoring • Two general categories of benefits to the activity of refactoring: Maintainability and Extensibility • 3 techniques for refactoring • Using tools for Code Refactoring • Code Refactoring are often used to improve quality and enhance project agility.
  • 24. Code Refactoring – TechTalks #6 24 Q&A
  • 25. Code Refactoring – TechTalks #6 25 References •Book: Improving the Design of Existing Code (by Martin Fowler) •Sites: • http://refactoring.com • http://en.wikipedia.org/wiki/Refactoring • http://wiki.netbeans.org/Refactoring • http://msdn.microsoft.com/en- us/library/ms379618(v=vs.80).aspx
  • 26. Code Refactoring – TechTalks #6 26 Thank you doipa@fpt.com.vn – khoanv4@fpt.com.vn

Editor's Notes

  1. Nguồn tham khảo: Java Refactoring Fest (presentation) - Naresh Jain - naresh@agilefaqs.comhttp://refactoring.comRefactoring workbook - William C. WakeRefactoring to Patterns - Joshua KerievskyRefactoring (presentation) - Jason Lee
  2. Improves the design of our softwareLoại bỏ những code tồiGiúp code dễ hiểu và dễ bảo trìTạo điều kiện thuận lợi cho các thay đổiTăng tính linh hoạtTăng khả năng tái sử dụng
  3. Cầncóvídụ
  4. Mỗikỹthuậtcầncómột demo
  5. Giới thiệu về một thiết kế (tồi) biểu diễn với UML trênĐới + Khoa (5 phút): thiết kế lại (đồng thời)So sánh 2 bản thiết kế mới của Đới và Khoa với bản ban đầuCùng sinh viên thảo luận, đánh giáDùng Netbeans triển khai theo thiết kế ban đầu và dùng các kỹ thuật Refactor có sẵn của Netbeans để thực hiện Refactor theo 2 bản thiết kế mới
  6. Ảnh từ: Slide của Naresh Jain