SlideShare a Scribd company logo
HOW TO MAKE YOUR CODE BETTER ::
REFACTORING
WHAT IS THIS TALK ABOUT?
Large apps are a completely different beast than small apps
    • Domain complexity
    • Tight code coupling across domain concepts
    •…



This talk is about working with large apps.


…   it’s about fixing code.
WHAT IS THIS TALK ABOUT?


…it’s about responsibility
fixing bad and improving
code.
WHAT IS GOOD CODE?



     There is no one
           ?
      right answer
WHAT IS A BAD CODE?
WHAT IS GOOD CODE…
“Any fool can write code that a computer can
understand. Good programmers write code that humans
can understand.”
                                       Martin Fowler
LET’S LOOK AT THIS PIECE OF
CODE
WHAT WE WANT?
•   Robustness
•   Simplicity
•   Softness



“Software must be soft: it has to be easy to change because
it will change despite our misguided efforts otherwise.”
                                  The Pragmatic Programmers
WHAT WE FREQUENTLY SEE? 
• Fragility
• Complexity
• Rigidity




As a result we have code that hard to
understand and modify.
WHAT IS REFACTORING???

“…process of changing a software system in such
a way that it does not after the external behavior of
the code yet implemented its internal structure.”
                                       Martin Fowler
WHY REFACTOR??
• Improve code structure and design
 • More maintainable
 • Easier to understand
 • Easier to modify
 • Easier to add new feature

• Understand code better and sometimes it helps to
  find bugs.


• Helps you develop better code, faster

       To get better code!!!
WHEN REFACTOR
• You add new features and the code is hard to
  understand
• You fix bug
• During code review


[!!!] Do not add new features during refactoring


… and sometimes you should throw things out
and start again.
WHAT DO WE NEED?
• If you want to refactor, the essential
  precondition is having solid tests
• Knowledge of full context
THE REFACTORING CYCLE
• Chose the worst smell
• Select a refactoring
• Apply the refactoring
• Run all the tests




!!! Do it using a little steps…
TYPICAL CODE SMELLS
• Duplicated code
• Large classes
• Long methods
• Long parameters list
• Feature envy
• Improper naming
• Comments
• Magic numbers
• etc…
CLASSES
• Long classes
• Code that isn’t executed
• Too many responsibilities
• Different abstraction level
• Variables and function should be defined close
to where they are used
• Using deprecated methods
• Useless comments
METHODS
• Long methods
• Deeply nested method
• Different abstraction level
• Method doesn’t perform
•   one identifiable task
• Long parameters list
• Many conditional statements
• Local variables should be declared just above
  their first usage
VARIABLES
• Instance variables are an implementation
  not an interface
• Bad variables name
• Magic numbers
• Several instances
COMMENTS
• Obsolete comments (Old comments that have lost their
  meaning)
• Redundant comments
  •   Version History
  •   Commented out code
  •   Repeating the variable name or condition in the comment
  •   Repeating the called method name in a comment after the call
  •   Comments related to structure
TYPICAL REFACTORINGS
Class               Method                  Variable

add (sub)class to   add method to class     add variable to class
hierarchy
rename class        rename method           rename variable

remove class        remove method           remove variable

                    push method down/push   push variable down
                    method up               pull variable up

                    add parameter to        create assessors
                    method

                    move method to          abstract variable
                    component
                    extract code in new
                    method
SAMPLES

WTF piece from our code.
??? QUESTIONS ???




Contact Information:
Olga Chursina

Email: O.Chursina@gmail.com
Skype: olga.chursina

More Related Content

What's hot

Bahaviour Driven Development
Bahaviour Driven DevelopmentBahaviour Driven Development
Bahaviour Driven Development
buildmaster
 
Improve your development skills with Test Driven Development
Improve your development skills with Test Driven DevelopmentImprove your development skills with Test Driven Development
Improve your development skills with Test Driven Development
John Stevenson
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Maris Prabhakaran M
 
Practical TDD Demonstrated
Practical TDD DemonstratedPractical TDD Demonstrated
Practical TDD Demonstrated
Alan Christensen
 
Основы функционального JS
Основы функционального JSОсновы функционального JS
Основы функционального JS
Анна Луць
 
Cucumber Tool
Cucumber ToolCucumber Tool
Cucumber Tool
Sohail Ahmed
 
Introduction to Bdd and cucumber
Introduction to Bdd and cucumberIntroduction to Bdd and cucumber
Introduction to Bdd and cucumber
Nibu Baby
 
Tatft
TatftTatft
Unit testing in PHP
Unit testing in PHPUnit testing in PHP
Unit testing in PHP
Chonlasith Jucksriporn
 
TDD In Practice
TDD In PracticeTDD In Practice
TDD In Practice
Alan Christensen
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
André Pitombeira
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Jitendra Zaa
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
Sargis Sargsyan
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
Milan Vukoje
 
Functional programmning
Functional programmningFunctional programmning
Functional programmning
Ayat_Khraisat
 
Journey with XP a case study in embedded domain by Pradeep Kumar NR
Journey with XP a case study in embedded domain  by Pradeep Kumar NRJourney with XP a case study in embedded domain  by Pradeep Kumar NR
Journey with XP a case study in embedded domain by Pradeep Kumar NR
XP Conference India
 
How To Write a Testable Code
How To Write a Testable CodeHow To Write a Testable Code
How To Write a Testable Code
OPIN Software Inc.
 
Test Automation Framework using Cucumber BDD overview (part 1)
Test Automation Framework using Cucumber BDD overview (part 1)Test Automation Framework using Cucumber BDD overview (part 1)
Test Automation Framework using Cucumber BDD overview (part 1)
Mindfire Solutions
 

What's hot (20)

Bahaviour Driven Development
Bahaviour Driven DevelopmentBahaviour Driven Development
Bahaviour Driven Development
 
Improve your development skills with Test Driven Development
Improve your development skills with Test Driven DevelopmentImprove your development skills with Test Driven Development
Improve your development skills with Test Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Practical TDD Demonstrated
Practical TDD DemonstratedPractical TDD Demonstrated
Practical TDD Demonstrated
 
Основы функционального JS
Основы функционального JSОсновы функционального JS
Основы функционального JS
 
Cucumber Tool
Cucumber ToolCucumber Tool
Cucumber Tool
 
Cucumber presenation
Cucumber presenationCucumber presenation
Cucumber presenation
 
Introduction to Bdd and cucumber
Introduction to Bdd and cucumberIntroduction to Bdd and cucumber
Introduction to Bdd and cucumber
 
Tatft
TatftTatft
Tatft
 
Unit testing in PHP
Unit testing in PHPUnit testing in PHP
Unit testing in PHP
 
TDD In Practice
TDD In PracticeTDD In Practice
TDD In Practice
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
Functional programmning
Functional programmningFunctional programmning
Functional programmning
 
Journey with XP a case study in embedded domain by Pradeep Kumar NR
Journey with XP a case study in embedded domain  by Pradeep Kumar NRJourney with XP a case study in embedded domain  by Pradeep Kumar NR
Journey with XP a case study in embedded domain by Pradeep Kumar NR
 
How To Write a Testable Code
How To Write a Testable CodeHow To Write a Testable Code
How To Write a Testable Code
 
Test Automation Framework using Cucumber BDD overview (part 1)
Test Automation Framework using Cucumber BDD overview (part 1)Test Automation Framework using Cucumber BDD overview (part 1)
Test Automation Framework using Cucumber BDD overview (part 1)
 
Automation and Technical Debt
Automation and Technical DebtAutomation and Technical Debt
Automation and Technical Debt
 

Viewers also liked

КРИ 2010: Социальные игры: вирусный маркетинг
КРИ 2010: Социальные игры: вирусный маркетингКРИ 2010: Социальные игры: вирусный маркетинг
КРИ 2010: Социальные игры: вирусный маркетингDenis Rysev
 
Globalvillage12 1
Globalvillage12 1Globalvillage12 1
Globalvillage12 1dibalfour
 
myonlinedocuments presentation
myonlinedocuments presentationmyonlinedocuments presentation
myonlinedocuments presentationStephHargreaves
 
0225 2003
0225 20030225 2003
0225 2003
Claudia Canales
 
Arlas brug af blogs og sociale medier
Arlas brug af blogs og sociale medierArlas brug af blogs og sociale medier
Arlas brug af blogs og sociale medier
Tanja Udengaard
 
Website Security
Website SecurityWebsite Security
Website Security
MODxpo
 
Beverage Warehousing Capabilities
Beverage Warehousing CapabilitiesBeverage Warehousing Capabilities
Beverage Warehousing CapabilitiesbwaitsGA
 
Arla's use of blogging and social media
Arla's use of blogging and social mediaArla's use of blogging and social media
Arla's use of blogging and social media
Tanja Udengaard
 

Viewers also liked (8)

КРИ 2010: Социальные игры: вирусный маркетинг
КРИ 2010: Социальные игры: вирусный маркетингКРИ 2010: Социальные игры: вирусный маркетинг
КРИ 2010: Социальные игры: вирусный маркетинг
 
Globalvillage12 1
Globalvillage12 1Globalvillage12 1
Globalvillage12 1
 
myonlinedocuments presentation
myonlinedocuments presentationmyonlinedocuments presentation
myonlinedocuments presentation
 
0225 2003
0225 20030225 2003
0225 2003
 
Arlas brug af blogs og sociale medier
Arlas brug af blogs og sociale medierArlas brug af blogs og sociale medier
Arlas brug af blogs og sociale medier
 
Website Security
Website SecurityWebsite Security
Website Security
 
Beverage Warehousing Capabilities
Beverage Warehousing CapabilitiesBeverage Warehousing Capabilities
Beverage Warehousing Capabilities
 
Arla's use of blogging and social media
Arla's use of blogging and social mediaArla's use of blogging and social media
Arla's use of blogging and social media
 

Similar to Refactoring

Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
Valerio Maggio
 
Clean Code
Clean CodeClean Code
Clean Code
swaraj Patil
 
Clean code
Clean codeClean code
Clean code
Simon Sönnby
 
Refactoring.pdf
Refactoring.pdfRefactoring.pdf
Refactoring.pdf
Mnats Karakhanyan
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
Mike Harris
 
Ruby code smells
Ruby code smellsRuby code smells
Ruby code smells
Rodrigo Urubatan
 
Code refactor strategy part #1
Code refactor strategy part #1Code refactor strategy part #1
Code refactor strategy part #1
Tracy LOISEL
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
Bhavin Gandhi
 
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Kaunas Java User Group
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approach
Enrico Da Ros
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문Sangcheol Hwang
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
AmalEldhose2
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
Pascal Larocque
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
Art of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices AntipatternsArt of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices Antipatterns
El Mahdi Benzekri
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
Pham Manh Lan
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
AgileNetwork
 
Applying Roles and Profiles method to compliance code
Applying Roles and Profiles method to compliance codeApplying Roles and Profiles method to compliance code
Applying Roles and Profiles method to compliance code
Puppet
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Sahar Nofal
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven developmentEinar Ingebrigtsen
 

Similar to Refactoring (20)

Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Refactoring.pdf
Refactoring.pdfRefactoring.pdf
Refactoring.pdf
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Ruby code smells
Ruby code smellsRuby code smells
Ruby code smells
 
Code refactor strategy part #1
Code refactor strategy part #1Code refactor strategy part #1
Code refactor strategy part #1
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approach
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Art of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices AntipatternsArt of refactoring - Code Smells and Microservices Antipatterns
Art of refactoring - Code Smells and Microservices Antipatterns
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
Applying Roles and Profiles method to compliance code
Applying Roles and Profiles method to compliance codeApplying Roles and Profiles method to compliance code
Applying Roles and Profiles method to compliance code
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven development
 

Recently uploaded

Deerfoot Church of Christ Bulletin 6 2 24
Deerfoot Church of Christ Bulletin 6 2 24Deerfoot Church of Christ Bulletin 6 2 24
Deerfoot Church of Christ Bulletin 6 2 24
deerfootcoc
 
St. John's Parish Magazine - June 2024 ..
St. John's Parish Magazine - June 2024 ..St. John's Parish Magazine - June 2024 ..
St. John's Parish Magazine - June 2024 ..
Chris Lyne
 
Lesson 9 - Resisting Temptation Along the Way.pptx
Lesson 9 - Resisting Temptation Along the Way.pptxLesson 9 - Resisting Temptation Along the Way.pptx
Lesson 9 - Resisting Temptation Along the Way.pptx
Celso Napoleon
 
Qualifications in psychology _Dr.Navis.pdf
Qualifications in psychology _Dr.Navis.pdfQualifications in psychology _Dr.Navis.pdf
Qualifications in psychology _Dr.Navis.pdf
Oavis Or
 
Kenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdf
Kenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdfKenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdf
Kenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdf
AlanBianch
 
The PBHP DYC ~ Reflections on The Dhamma (English).pptx
The PBHP DYC ~ Reflections on The Dhamma (English).pptxThe PBHP DYC ~ Reflections on The Dhamma (English).pptx
The PBHP DYC ~ Reflections on The Dhamma (English).pptx
OH TEIK BIN
 
Exploring the Mindfulness Understanding Its Benefits.pptx
Exploring the Mindfulness Understanding Its Benefits.pptxExploring the Mindfulness Understanding Its Benefits.pptx
Exploring the Mindfulness Understanding Its Benefits.pptx
MartaLoveguard
 
Evangelization in the footsteps of Saint Vincent de Paul
Evangelization in the footsteps of Saint Vincent de PaulEvangelization in the footsteps of Saint Vincent de Paul
Evangelization in the footsteps of Saint Vincent de Paul
Famvin: the Worldwide Vincentian Family
 
The Chakra System in our body - A Portal to Interdimensional Consciousness.pptx
The Chakra System in our body - A Portal to Interdimensional Consciousness.pptxThe Chakra System in our body - A Portal to Interdimensional Consciousness.pptx
The Chakra System in our body - A Portal to Interdimensional Consciousness.pptx
Bharat Technology
 
English - The Book of Joshua the Son of Nun.pdf
English - The Book of Joshua the Son of Nun.pdfEnglish - The Book of Joshua the Son of Nun.pdf
English - The Book of Joshua the Son of Nun.pdf
Filipino Tracts and Literature Society Inc.
 
The Good News, newsletter for June 2024 is here
The Good News, newsletter for June 2024 is hereThe Good News, newsletter for June 2024 is here
The Good News, newsletter for June 2024 is here
NoHo FUMC
 
HANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLD
HANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLDHANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLD
HANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLD
Learnyoga
 
What Should be the Christian View of Anime?
What Should be the Christian View of Anime?What Should be the Christian View of Anime?
What Should be the Christian View of Anime?
Joe Muraguri
 
Jesus Heals a Paralyzed Man for Children
Jesus Heals a Paralyzed Man for ChildrenJesus Heals a Paralyzed Man for Children
Jesus Heals a Paralyzed Man for Children
NelTorrente
 
Tarot for Your Self A Workbook for Personal Transformation Second Edition (M...
Tarot for Your Self  A Workbook for Personal Transformation Second Edition (M...Tarot for Your Self  A Workbook for Personal Transformation Second Edition (M...
Tarot for Your Self A Workbook for Personal Transformation Second Edition (M...
Mark457009
 
St John's Parish Diary for June 2024.pdf
St John's Parish Diary for June 2024.pdfSt John's Parish Diary for June 2024.pdf
St John's Parish Diary for June 2024.pdf
Chris Lyne
 
Jude: Practical Exhortations_Jude 17-23.pptx
Jude: Practical Exhortations_Jude 17-23.pptxJude: Practical Exhortations_Jude 17-23.pptx
Jude: Practical Exhortations_Jude 17-23.pptx
Stephen Palm
 

Recently uploaded (17)

Deerfoot Church of Christ Bulletin 6 2 24
Deerfoot Church of Christ Bulletin 6 2 24Deerfoot Church of Christ Bulletin 6 2 24
Deerfoot Church of Christ Bulletin 6 2 24
 
St. John's Parish Magazine - June 2024 ..
St. John's Parish Magazine - June 2024 ..St. John's Parish Magazine - June 2024 ..
St. John's Parish Magazine - June 2024 ..
 
Lesson 9 - Resisting Temptation Along the Way.pptx
Lesson 9 - Resisting Temptation Along the Way.pptxLesson 9 - Resisting Temptation Along the Way.pptx
Lesson 9 - Resisting Temptation Along the Way.pptx
 
Qualifications in psychology _Dr.Navis.pdf
Qualifications in psychology _Dr.Navis.pdfQualifications in psychology _Dr.Navis.pdf
Qualifications in psychology _Dr.Navis.pdf
 
Kenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdf
Kenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdfKenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdf
Kenneth Grant - Against the Light-Holmes Pub Grou Llc (1999).pdf
 
The PBHP DYC ~ Reflections on The Dhamma (English).pptx
The PBHP DYC ~ Reflections on The Dhamma (English).pptxThe PBHP DYC ~ Reflections on The Dhamma (English).pptx
The PBHP DYC ~ Reflections on The Dhamma (English).pptx
 
Exploring the Mindfulness Understanding Its Benefits.pptx
Exploring the Mindfulness Understanding Its Benefits.pptxExploring the Mindfulness Understanding Its Benefits.pptx
Exploring the Mindfulness Understanding Its Benefits.pptx
 
Evangelization in the footsteps of Saint Vincent de Paul
Evangelization in the footsteps of Saint Vincent de PaulEvangelization in the footsteps of Saint Vincent de Paul
Evangelization in the footsteps of Saint Vincent de Paul
 
The Chakra System in our body - A Portal to Interdimensional Consciousness.pptx
The Chakra System in our body - A Portal to Interdimensional Consciousness.pptxThe Chakra System in our body - A Portal to Interdimensional Consciousness.pptx
The Chakra System in our body - A Portal to Interdimensional Consciousness.pptx
 
English - The Book of Joshua the Son of Nun.pdf
English - The Book of Joshua the Son of Nun.pdfEnglish - The Book of Joshua the Son of Nun.pdf
English - The Book of Joshua the Son of Nun.pdf
 
The Good News, newsletter for June 2024 is here
The Good News, newsletter for June 2024 is hereThe Good News, newsletter for June 2024 is here
The Good News, newsletter for June 2024 is here
 
HANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLD
HANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLDHANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLD
HANUMAN STORIES: TIMELESS TEACHINGS FOR TODAY’S WORLD
 
What Should be the Christian View of Anime?
What Should be the Christian View of Anime?What Should be the Christian View of Anime?
What Should be the Christian View of Anime?
 
Jesus Heals a Paralyzed Man for Children
Jesus Heals a Paralyzed Man for ChildrenJesus Heals a Paralyzed Man for Children
Jesus Heals a Paralyzed Man for Children
 
Tarot for Your Self A Workbook for Personal Transformation Second Edition (M...
Tarot for Your Self  A Workbook for Personal Transformation Second Edition (M...Tarot for Your Self  A Workbook for Personal Transformation Second Edition (M...
Tarot for Your Self A Workbook for Personal Transformation Second Edition (M...
 
St John's Parish Diary for June 2024.pdf
St John's Parish Diary for June 2024.pdfSt John's Parish Diary for June 2024.pdf
St John's Parish Diary for June 2024.pdf
 
Jude: Practical Exhortations_Jude 17-23.pptx
Jude: Practical Exhortations_Jude 17-23.pptxJude: Practical Exhortations_Jude 17-23.pptx
Jude: Practical Exhortations_Jude 17-23.pptx
 

Refactoring

  • 1. HOW TO MAKE YOUR CODE BETTER :: REFACTORING
  • 2. WHAT IS THIS TALK ABOUT? Large apps are a completely different beast than small apps • Domain complexity • Tight code coupling across domain concepts •… This talk is about working with large apps. … it’s about fixing code.
  • 3. WHAT IS THIS TALK ABOUT? …it’s about responsibility fixing bad and improving code.
  • 4. WHAT IS GOOD CODE? There is no one ? right answer
  • 5. WHAT IS A BAD CODE?
  • 6. WHAT IS GOOD CODE… “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” Martin Fowler
  • 7. LET’S LOOK AT THIS PIECE OF CODE
  • 8. WHAT WE WANT? • Robustness • Simplicity • Softness “Software must be soft: it has to be easy to change because it will change despite our misguided efforts otherwise.” The Pragmatic Programmers
  • 9. WHAT WE FREQUENTLY SEE?  • Fragility • Complexity • Rigidity As a result we have code that hard to understand and modify.
  • 10. WHAT IS REFACTORING??? “…process of changing a software system in such a way that it does not after the external behavior of the code yet implemented its internal structure.” Martin Fowler
  • 11. WHY REFACTOR?? • Improve code structure and design • More maintainable • Easier to understand • Easier to modify • Easier to add new feature • Understand code better and sometimes it helps to find bugs. • Helps you develop better code, faster To get better code!!!
  • 12. WHEN REFACTOR • You add new features and the code is hard to understand • You fix bug • During code review [!!!] Do not add new features during refactoring … and sometimes you should throw things out and start again.
  • 13. WHAT DO WE NEED? • If you want to refactor, the essential precondition is having solid tests • Knowledge of full context
  • 14. THE REFACTORING CYCLE • Chose the worst smell • Select a refactoring • Apply the refactoring • Run all the tests !!! Do it using a little steps…
  • 15. TYPICAL CODE SMELLS • Duplicated code • Large classes • Long methods • Long parameters list • Feature envy • Improper naming • Comments • Magic numbers • etc…
  • 16. CLASSES • Long classes • Code that isn’t executed • Too many responsibilities • Different abstraction level • Variables and function should be defined close to where they are used • Using deprecated methods • Useless comments
  • 17. METHODS • Long methods • Deeply nested method • Different abstraction level • Method doesn’t perform • one identifiable task • Long parameters list • Many conditional statements • Local variables should be declared just above their first usage
  • 18. VARIABLES • Instance variables are an implementation not an interface • Bad variables name • Magic numbers • Several instances
  • 19. COMMENTS • Obsolete comments (Old comments that have lost their meaning) • Redundant comments • Version History • Commented out code • Repeating the variable name or condition in the comment • Repeating the called method name in a comment after the call • Comments related to structure
  • 20. TYPICAL REFACTORINGS Class Method Variable add (sub)class to add method to class add variable to class hierarchy rename class rename method rename variable remove class remove method remove variable push method down/push push variable down method up pull variable up add parameter to create assessors method move method to abstract variable component extract code in new method
  • 22. ??? QUESTIONS ??? Contact Information: Olga Chursina Email: O.Chursina@gmail.com Skype: olga.chursina

Editor's Notes

  1. RearchitectingAs you increase your knowledge of the code, making it more comprehensible and better factored, you'll inevitably find some bits you don't like. When you started this project, you weren't really capable of changing much, but now you've played with the code, and it's not as damaged as it once was. Along the way, you have seen some bad things and had some ideas on how to fix them. It's time to make some serious changes. Rewrite code you don't understandIf you know what the code should do, and it seems to do it, but you can't figure out quite how, it's bad code. If the original author did something tricky, some comments should have been provided. More likely though, the author was clueless and the code really is a disaster. Rewrite it. By rewriting the code, you have the opportunity to do it the easy way, and to include useful comments. Start by writing down in Javadoc comments what the new code does (just to make sure that you know). Then you can take advantage of the byproducts of your refactoring: call this new method that does that, use that new data structure to store this. The new code will make more sense to everybody and will probably run faster as well. Your unit tests will tell you whether your new code works. Go into your bug tracking system and close all the bugs you have fixed. Move to a layered architectureLet's hope that your inherited, formerly bad code now looks better. It's time to look at the bigger picture: how the packages relate to each other. Using some sort of tool that tells you what classes invoke what methods (that information can be extracted from the class files), find out the interclass dependencies. From those dependencies, infer the interpackage dependencies. If you can't draw a hierarchy (without any loops!) of what packages depend on what other packages, you have some architectural work to do. Using your instincts, a code browser, and a great deal of guesswork, figure out what such an architecture might look like one fine day. Then identify the particular problem spots. A particular class that frequently refers to other packages or a particular constant referred to from other packages hints that classes or parts of classes reside in the wrong package. Ask yourself whether it would make sense to move that code to another package. After a lot of consideration, you can derive a package hierarchy that looks sensible. Although it may require a lot of work to achieve the clean architecture, it gives you a goal to work toward. Your unit tests have clarified what the code should do, and now the architecture allocates the responsibility to do it to packages and classes. All you have to do is fill in the code.
  2. Break up big methodsJust as big classes prove difficult to understand, so do big methods, whose usual causes include:Too many options, causing the method to do too many thingsNot enough support from other methods, causing the method to do tasks at a lower level than it shouldOverly complicated exception handlingMy rule of thumb for methods: If I can't fit the entire thing on one screen, it's too long. It's an entirely practical rule with no theoretical basis, but it seems right and works for me. Remember though, when you read a method of 100 statements for the first time, it looks like 100 unrelated statements, and it is only after some study that you can see the internal structure. Life would be easier for you and for others if you made that internal structure explicit.
  3. Fix the Javadoc commentsYou never realize a comment's importance until you need to read it. Even if nobody else reads it (and usually, they don't), Javadoc comments are important for the code authors to help them remember what the code/class/parameter should do. Pieces of information particularly important to include are: Whether an object parameter may be null, and what it means if it isWhether a parameter needs to be mutable or notWhether a return value is mutableWhether a return value may be nullWhether changes to the return value affect the returner's internal stateFixing the Javadoc comments doesn't mean just adding them where there were none before. You should also delete misleading and trivial comments (such as documenting setters and getters) as they engender a false sense of security. Important information exists for inclusion in Javadoc comments, so there's no point wasting the time of potential readers. When you write new methods and classes, try to include some Javadoc comments (just a few) to explain what they do. Even if it's obvious to you, the next person to get the code might thank you for the effort. If you don't know what to write in the Javadoc comments, you have no business writing the code. Javadoc comments can also serve as a record of what you learned about the code. When you figure out what a particularly tricky, clever, or ugly method does (especially a private or protected method with no implied contract), write a comment to record it for posterity. This expands the amount of the code under your control and helps you later when you're trying to decipher something related. Of course, Javadoc comments should only explain the effect of a method, never the implementation (because you might change that). If code within a method needs explanation, use standard code comments. A school of thought exists that says with good enough identifiers you don't need code comments at all. I'm not that extreme, but I take the point. Indeed, many code comments don't tell you anything new. I urge you to leave those uninformative comments out, as they only serve to make simple code verbose and intimidating.