SlideShare a Scribd company logo
Refactoring
Therapeutic Attitude to Programming
12/23/2017 Refactoring 1
Amin Shahnazari
University of Isfahan
uestions
12/23/2017 Refactoring 2
1. What is the most terrible thing to a
programmer?
2. What are the common programming
diseases?
12/23/2017 Refactoring 3
1. What is the most terrible thing to a programmer?
- Clean code
- Technical debt
- Refactoring definition
- Why should you refactor?
- When Should you refactor?
- Learning Refactoring.
2. What are the common programming diseases?
- Bloaters
- Object Oriented Abuses
- Change Obstacles
- Redundancies
- Couplings
Table of
Content
uestions
12/23/2017 Refactoring 4
MOST TERRIBLE
What is
thing to a programmer?
the
Question 1:
12/23/2017 Refactoring 5
Change!
Requirements
Technologies
Priorities
Teams
Companies
Bugs
Features
Everythingwillbechanged!
NO
--Say--
to Evil
12/23/2017 Refactoring 6
Old Wrong Engineering Mentality:
If it works, Don’t fix it!
Think about
tomorrow!
Consider
Changes!
12/23/2017 Refactoring 7
Clean Code
• Clean code is obvious for other programmers.
All of that makes code sloppy and difficult to grasp should resolve.
• Clean code doesn't contain duplication or redundant code.
This increases the cognitive load and slows down the progress.
• Clean code contains a minimal number of classes and other
moving parts.
Less code = Less stuff to keep in your head, Less maintenance, Fewer bugs.
• Clean code passes all tests.
How can we maintain and extend code without the fear that it will stop
working? You cannot test dirty code!
• Clean code has minimal dependencies!
The more dependencies it has, the harder it is to maintain and change it in
the future.
12/23/2017 Refactoring 8
Technical debt
If you get a loan from a bank:
• This allows you to make purchases faster.
• You pay extra for expediting the process.
• If the amount of interest exceeds your total income,
making full repayment impossible.
The same thing can happen with code:
• You can temporarily speed up with dirty code (debt).
• This will gradually slow your progress every day.
• You have to eventually pay off the debt.
• I hope that you can pay off debt successfully.
12/23/2017 Refactoring 9
Cause of
Technical
debt
• Business pressure.
• Lack of understanding of the consequences of technical debt.
• Failing to combat the strict coherence of components.
• Lack of tests.
• Lack of documentation.
• Lack of interaction between team members.
• Long-term simultaneous development in several branches.
• Lack of compliance monitoring.
• Programmer incompetence.
12/23/2017 Refactoring 10
Refactoring definition
• It is a disciplined way to clean up code that minimizes
the chances of introducing bugs.
• In essence when you refactor you are improving the
design of the code after it has been written.
• It’s not about performance optimization.
“Refactoring is the process of changing a software
system in such a way that it does not alter the
external behavior of the code yet improves its
internal structure.” --Martin Fowler--
12/23/2017 Refactoring 11
Why
should you
refactor?
• Refactoring Improves the Design of Software.
Without refactoring, the design of the program will decay.
As people change codes, the code loses its structure.
Loss of the structure of code has a cumulative effect.
• Refactoring Makes Software Easier to Understand.
Think about future developer! Often this future developer is you!
Programs that are hard to read are hard to modify.
• Refactoring Helps You Find Bugs.
Refactoring is rather like tidying up the code.
If I refactor code, I work deeply on understanding what the code does.
By clarifying the structure, you clarify assumptions you’ve made.
• Refactoring Helps You Program Faster.
Without a good design you progress quickly for a while, but soon the poor
design start to slow you down.
You spend more time to find and fix the bugs and changes takes time.
12/23/2017 Refactoring 12
When
should you
refactor?
• Refactoring When Add Feature.
Helps to understand some code which needs modification.
When there is a design that does not help add a feature easily.
• Refactoring When You Need to Fix a Bug.
Refactor to help improve understanding.
• Refactoring As You Do a Code Review.
Code review help spread knowledge through a development team.
The last chance to tidy up the code before it becomes available to the
public.
It's best to perform such reviews in a pair with an author.
12/23/2017 Refactoring 13
What
Do I Tell My
Manager?
• Quality Driven Manager:
It’s not so difficult, implement refactoring in review process.
• Schedule Driven Manager:
The fastest way is to refactor, therefore I refactor!
• Quality-Schedule Manager:
Don’t tell!
12/23/2017 Refactoring 14
Refactoring, Improve
the Design of Existing
Code
Learning
Refactoring
Martin Fowler
and Et al.
https://refactoring.guru
Refactoring Guru
website
12/23/2017 Refactoring 15
Learning
Refactoring
Martin Fowler
1963 (age 53–54)
Kent Beck
1961 (age 55–56)
uestions
12/23/2017 Refactoring 16
DISEASES?
What are the common programming
Question 2:
12/23/2017 Refactoring 17
Refactoring is a therapeutic attitude to
programming diseases!
• Just like a medical doctor, you need to cure
these diseases.
• You need to detect diseases from signs in codes.
• A list of common diseases and their treatments
already provided.
• In refactoring nomenclature, diseases called
Code Bad Smells.
12/23/2017 Refactoring 18
5
• Bloaters
Code, methods and classes that have increased to such huge
proportions that they are hard to work with.
Class
of diseases
• Object Oriented Abuses
Incomplete or incorrect application of object-oriented programming
principles.
• Change Obstacles
If you need to change something in one place in your code, you have to make
many changes in other places too.
• Redundancies
Some pointless and unneeded codes whose absence would make the code
cleaner, more efficient and easier to understand.
• Couplings
Excessive coupling between classes.
12/23/2017 Refactoring 19
Bloaters
• Long Methods
• Large Classes
• Primitive Obsession
• Long Parameter List
• Data Clumps
12/23/2017 Refactoring 20
Long Method
Bloaters
• A method contains too many lines of code.
• Generally, any method longer than ten lines should make
you start asking questions.
• If you feel need to comment something in a method, write
a method instead.
Signs
Reason
Treatment
• Since it is easier to write code than to read it, this "smell"
remains unnoticed until the method turns into an ugly.
• Extract Method, Replace Temp with Query, Introduce
Parameter Object.
• Preserve Whole Object, Replace Method with Method
Object.
• Decompose Conditional.
12/23/2017 Refactoring 21
Large Class
Bloaters
• A class contains many fields/methods/lines of code.Signs
Reason
Treatment
• Programmers usually find it mentally less taxing to place a
new feature in an existing class than to create a new class
for the feature.
• Class has several responsibilities.
• Extract Class
• Extract Subclass
• Extract Interface
• Duplicate Observed Data
12/23/2017 Refactoring 22
Primitive Obsession
Bloaters
• Use of primitives instead of small objects for simple tasks.
• Use of constants for coding information.
• Use of string constants as field names for use in data
arrays.
Signs
Reason
Treatment
• "Just a field for storing some data!" the programmer said.
• Creating a primitive field is so much easier than making a
whole new class,
• Replace Data Value with Object.
• Introduce Parameter Object, Preserve Whole Object.
• Replace Type Code with Class, Replace Type Code with
Subclasses or Replace Type Code with State/Strategy.
• Replace Array with Object.
12/23/2017 Refactoring 23
Long Parameter List
Bloaters
• More than three or four parameters for a method.Signs
Reason
Treatment
• A long list of parameters might happen after several types
of algorithms are merged in a single method.
• Replace Parameter with Method Call.
• Preserve Whole Object.
• Introduce Parameter Object.
12/23/2017 Refactoring 24
Bloaters
• Sometimes different parts of the code contain identical
groups of variables.
Signs
Reason
Treatment
• Often these data groups are due to poor program structure
or "copy-paste programming”.
• Just delete one of the data values and see whether the
other values still make sense. If this is not the case, this is a
good sign that this group of variables should be combined
into an object.
• Extract Class
• Introduce Parameter Object
• Preserve Whole Object
Data Clumps
12/23/2017 Refactoring 25
OO Abuses
• Switch Statements
• Temporary Field
• Refused Bequest
• Alternative Classes with
Different Interfaces
12/23/2017 Refactoring 26
OOAbuses
• You have a complex switch operator or sequence of if
statements.
Signs
Reason
Treatment
• Often code for a single switch can be scattered in different
places in the program. When a new condition is added, you
have to find all the switch code and modify it.
• when you see switch you should think of polymorphism.
• Extract Method, Move Method.
• Replace Type Code with Subclasses
• Replace Type Code with State/Strategy.
• Replace Conditional with Polymorphism.
• Replace Parameter with Explicit Methods.
• Introduce Null Object.
Switch Statements
12/23/2017 Refactoring 27
OOAbuses
• Temporary fields get their values only under certain
circumstances. Outside of these circumstances, they are
empty.
Signs
Reason
Treatment
• Oftentimes, temporary fields are created for use in an
algorithm that requires a large amount of inputs.
• These fields are used only in the algorithm and go unused
the rest of the time.
• Extract Class.
• Replace Method with Method Object.
• Introduce Null Object
Temporary Field
12/23/2017 Refactoring 28
OOAbuses
• If a subclass uses only some of the methods and properties
inherited from its parents, the hierarchy is off-kilter.
Signs
Reason
Treatment
• Someone was motivated to create inheritance between
classes only by the desire to reuse the code in a superclass.
But the superclass and subclass are completely different.
• Replace Inheritance with Delegation.
• Extract Superclass
Refused Bequest
12/23/2017 Refactoring 29
OOAbuses
• Two classes perform identical functions but have different
method names.
Signs
Reason
Treatment
• The programmer who created one of the classes probably
didn't know that a functionally equivalent class already
existed.
• Rename Method
• Move Method, Add Parameter
• Parameterize Method.
• Extract Superclass.
Alternative Classes with Different Interfaces
12/23/2017 Refactoring 30
Change Obstacles
• Divergent Change
• Shotgun Surgery
• Parallel Inheritance
Hierarchies
12/23/2017 Refactoring 31
ChangeObst
• You find yourself having to change many unrelated
methods when you make changes to a class.
Signs
Reason
Treatment
• Often these divergent modifications are due to poor
program structure or "copy-paste programming”.
• Extract Class.
• Extract Superclass
• Extract Subclass
Divergent Change
12/23/2017 Refactoring 32
ChangeObst
• Making any modifications requires that you make many
small changes to many different classes.
Signs
Reason
Treatment
• A single responsibility has been split up among a large
number of classes.
• Move Method
• Move Field
• Inline Class
Shotgun Surgery
12/23/2017 Refactoring 33
ChangeObst
• Whenever you create a subclass for a class, you find
yourself needing to create a subclass for another class.
Signs
Reason
Treatment
• All was well as long as the hierarchy stayed small. But
with new classes being added, making changes has
become harder and harder.
• Move Method
• Move Field.
Parallel Inheritance Hierarchies
12/23/2017 Refactoring 34
Redundancies
• Comments
• Data Class
• Lazy Class
• Duplicate Code
• Dead Code
• Speculative Generality
12/23/2017 Refactoring 35
Redundancies
• A method is filled with explanatory comments.Signs
Reason
Treatment
• If you feel that a code fragment cannot be understood
without comments, try to change the code structure in a
way that makes comments unnecessary.
• The best comment is a good name for a method or class.
• Extract Variable.
• Extract Method.
• Rename Method
• Introduce Assertion.
Comments
12/23/2017 Refactoring 36
Redundancies
• Two code fragments look almost identical.Signs
Reason
Treatment
• Duplication usually occurs when multiple programmers are
working on different parts of the same program at the
same time.
• Extract Method, Pull Up Field
• Pull Up Constructor Body.
• Form Template Method.
• Substitute Algorithm
• Extract Superclass, Extract Class
• Consolidate Conditional Expression
• Consolidate Duplicate Conditional
Fragments.
Duplicate Code
12/23/2017 Refactoring 37
Redundancies
• So if a class doesn't do enough to earn your attention, it
should be deleted.
Signs
Reason
Treatment
• Perhaps a class was designed to be fully functional but
after some of the refactoring it has become small.
• Inline Class
• Collapse Hierarchy
Lazy Class
12/23/2017 Refactoring 38
Redundancies
• A data class refers to a class that contains only fields and
crude methods for accessing them (getters and setters).
Signs
Reason
Treatment
• But the true power of objects is that they can contain
behavior types or operations on their data.
• Encapsulate Field
• Encapsulate Collection
• Move Method, Extract Method
• Remove Setting Method, Hide Method
Data Class
12/23/2017 Refactoring 39
Redundancies
• A variable, parameter, field, method or class is no longer
used.
Signs
Reason
Treatment
• When requirements for the software have changed or
corrections have been made, nobody had time to clean up
the old code.
• Using IDE.
• Inline Class, Collapse Hierarchy
• Remove Parameter
Dead Code
12/23/2017 Refactoring 40
Redundancies
• There is an unused class, method, field or parameter.Signs
Reason
Treatment
• Sometimes code is created "just in case"
to support anticipated future features
that never get implemented.
• Collapse Hierarchy.
• Inline Class.
• Inline Method
• Remove Parameter.
Speculative Generality
12/23/2017 Refactoring 41
Couplings
• Feature Envy
• Incomplete Library Class
• Middle Man
• Inappropriate Intimacy
• Message Chains
12/23/2017 Refactoring 42
Couplings
• A method accesses the data of another object more than
its own data.
Signs
Reason
Treatment
• This smell may occur after fields are
moved to a data class. If this is the case,
you may want to move the operations on
data to this class as well.
• Move Method
• Extract Method
Feature Envy
12/23/2017 Refactoring 43
• One class uses the internal fields and methods of another
class.
Signs
Reason
Treatment
• Keep a close eye on classes that spend
too much time together.
• Good classes should know as little about
each other as possible.
• Move Method, Move Field
• Extract Class, Hide Delegate
• Change Bidirectional Association
to Unidirectional.
• Replace Delegation with Inheritance.
Inappropriate Intimacy
Couplings
12/23/2017 Refactoring 44
• In code you see a series of calls resembling $a->b()->c()->d()Signs
Reason
Treatment
• A message chain occurs when a client requests
another object, that object requests yet another
one, and so on.
• These chains mean that the client is dependent
on navigation along the class structure
• Hide Delegate.
• Extract Method
• Move Method.
Message Chains
Couplings
12/23/2017 Refactoring 45
• If a class performs only one action, delegating work to
another class, why does it exist at all?
Signs
Reason
Treatment
• In other cases, it can be the result of the useful
work of a class being gradually moved to other
classes.
• The class remains as an empty shell that does not
do anything other than delegate.
• Remove Middle Man
Middle Man
Couplings
12/23/2017 Refactoring 46
Thanks For your attentions

More Related Content

What's hot (7)

PDF
Put to the Test
Kevlin Henney
 
PDF
CMSC 335 FINAL PROJECT
HamesKellor
 
PDF
The testing skillset
Johan Hoberg
 
PDF
Test driven development vs Behavior driven development
Gallop Solutions
 
PDF
Test Driven Development
Hicham El Hammouchi
 
PPT
Test drive on driven development process
Muralidharan Deenathayalan
 
PPTX
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
Put to the Test
Kevlin Henney
 
CMSC 335 FINAL PROJECT
HamesKellor
 
The testing skillset
Johan Hoberg
 
Test driven development vs Behavior driven development
Gallop Solutions
 
Test Driven Development
Hicham El Hammouchi
 
Test drive on driven development process
Muralidharan Deenathayalan
 
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 

Similar to Refactoring, Therapeutic Attitude to Programming. (20)

PDF
Refactoring: Improve the design of existing code
Valerio Maggio
 
PDF
Refactoring 2TheMax (con ReSharper)
DotNetMarche
 
PPT
Principles in Refactoring
Chamnap Chhorn
 
PDF
Refactoring.pdf
Mnats Karakhanyan
 
PDF
Code Refactoring in Software Development
philipthomas428223
 
PPT
Principlesinrefactoring 090906230021-phpapp01
Sopheak Sem
 
PPTX
Refactoring
ochursina
 
PPTX
Refactoring
Rabeya Bashri
 
PDF
Improving your code design using Java
Roan Brasil Monteiro
 
PPTX
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Cefalo
 
PPTX
SAD10 - Refactoring
Michael Heron
 
PPTX
Refactoring
Arman Sheikh
 
PDF
Code Refactoring
kim.mens
 
ODP
Refactoring: Improving the design of existing code
Knoldus Inc.
 
PDF
Refactoring
Xavier Fornés Arrabal
 
PPT
Code Refactoring
Charlie Berg
 
PPTX
Refactoring
AngelLuisBlasco
 
PPTX
Refactoring, 2nd Edition
jexp
 
PPT
Refactoring Tips by Martin Fowler
Igor Crvenov
 
PPTX
Refactoring workshop
Itzik Saban
 
Refactoring: Improve the design of existing code
Valerio Maggio
 
Refactoring 2TheMax (con ReSharper)
DotNetMarche
 
Principles in Refactoring
Chamnap Chhorn
 
Refactoring.pdf
Mnats Karakhanyan
 
Code Refactoring in Software Development
philipthomas428223
 
Principlesinrefactoring 090906230021-phpapp01
Sopheak Sem
 
Refactoring
ochursina
 
Refactoring
Rabeya Bashri
 
Improving your code design using Java
Roan Brasil Monteiro
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Cefalo
 
SAD10 - Refactoring
Michael Heron
 
Refactoring
Arman Sheikh
 
Code Refactoring
kim.mens
 
Refactoring: Improving the design of existing code
Knoldus Inc.
 
Code Refactoring
Charlie Berg
 
Refactoring
AngelLuisBlasco
 
Refactoring, 2nd Edition
jexp
 
Refactoring Tips by Martin Fowler
Igor Crvenov
 
Refactoring workshop
Itzik Saban
 
Ad

Recently uploaded (20)

PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Ad

Refactoring, Therapeutic Attitude to Programming.

  • 1. Refactoring Therapeutic Attitude to Programming 12/23/2017 Refactoring 1 Amin Shahnazari University of Isfahan
  • 2. uestions 12/23/2017 Refactoring 2 1. What is the most terrible thing to a programmer? 2. What are the common programming diseases?
  • 3. 12/23/2017 Refactoring 3 1. What is the most terrible thing to a programmer? - Clean code - Technical debt - Refactoring definition - Why should you refactor? - When Should you refactor? - Learning Refactoring. 2. What are the common programming diseases? - Bloaters - Object Oriented Abuses - Change Obstacles - Redundancies - Couplings Table of Content
  • 4. uestions 12/23/2017 Refactoring 4 MOST TERRIBLE What is thing to a programmer? the Question 1:
  • 6. NO --Say-- to Evil 12/23/2017 Refactoring 6 Old Wrong Engineering Mentality: If it works, Don’t fix it! Think about tomorrow! Consider Changes!
  • 7. 12/23/2017 Refactoring 7 Clean Code • Clean code is obvious for other programmers. All of that makes code sloppy and difficult to grasp should resolve. • Clean code doesn't contain duplication or redundant code. This increases the cognitive load and slows down the progress. • Clean code contains a minimal number of classes and other moving parts. Less code = Less stuff to keep in your head, Less maintenance, Fewer bugs. • Clean code passes all tests. How can we maintain and extend code without the fear that it will stop working? You cannot test dirty code! • Clean code has minimal dependencies! The more dependencies it has, the harder it is to maintain and change it in the future.
  • 8. 12/23/2017 Refactoring 8 Technical debt If you get a loan from a bank: • This allows you to make purchases faster. • You pay extra for expediting the process. • If the amount of interest exceeds your total income, making full repayment impossible. The same thing can happen with code: • You can temporarily speed up with dirty code (debt). • This will gradually slow your progress every day. • You have to eventually pay off the debt. • I hope that you can pay off debt successfully.
  • 9. 12/23/2017 Refactoring 9 Cause of Technical debt • Business pressure. • Lack of understanding of the consequences of technical debt. • Failing to combat the strict coherence of components. • Lack of tests. • Lack of documentation. • Lack of interaction between team members. • Long-term simultaneous development in several branches. • Lack of compliance monitoring. • Programmer incompetence.
  • 10. 12/23/2017 Refactoring 10 Refactoring definition • It is a disciplined way to clean up code that minimizes the chances of introducing bugs. • In essence when you refactor you are improving the design of the code after it has been written. • It’s not about performance optimization. “Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.” --Martin Fowler--
  • 11. 12/23/2017 Refactoring 11 Why should you refactor? • Refactoring Improves the Design of Software. Without refactoring, the design of the program will decay. As people change codes, the code loses its structure. Loss of the structure of code has a cumulative effect. • Refactoring Makes Software Easier to Understand. Think about future developer! Often this future developer is you! Programs that are hard to read are hard to modify. • Refactoring Helps You Find Bugs. Refactoring is rather like tidying up the code. If I refactor code, I work deeply on understanding what the code does. By clarifying the structure, you clarify assumptions you’ve made. • Refactoring Helps You Program Faster. Without a good design you progress quickly for a while, but soon the poor design start to slow you down. You spend more time to find and fix the bugs and changes takes time.
  • 12. 12/23/2017 Refactoring 12 When should you refactor? • Refactoring When Add Feature. Helps to understand some code which needs modification. When there is a design that does not help add a feature easily. • Refactoring When You Need to Fix a Bug. Refactor to help improve understanding. • Refactoring As You Do a Code Review. Code review help spread knowledge through a development team. The last chance to tidy up the code before it becomes available to the public. It's best to perform such reviews in a pair with an author.
  • 13. 12/23/2017 Refactoring 13 What Do I Tell My Manager? • Quality Driven Manager: It’s not so difficult, implement refactoring in review process. • Schedule Driven Manager: The fastest way is to refactor, therefore I refactor! • Quality-Schedule Manager: Don’t tell!
  • 14. 12/23/2017 Refactoring 14 Refactoring, Improve the Design of Existing Code Learning Refactoring Martin Fowler and Et al. https://refactoring.guru Refactoring Guru website
  • 15. 12/23/2017 Refactoring 15 Learning Refactoring Martin Fowler 1963 (age 53–54) Kent Beck 1961 (age 55–56)
  • 16. uestions 12/23/2017 Refactoring 16 DISEASES? What are the common programming Question 2:
  • 17. 12/23/2017 Refactoring 17 Refactoring is a therapeutic attitude to programming diseases! • Just like a medical doctor, you need to cure these diseases. • You need to detect diseases from signs in codes. • A list of common diseases and their treatments already provided. • In refactoring nomenclature, diseases called Code Bad Smells.
  • 18. 12/23/2017 Refactoring 18 5 • Bloaters Code, methods and classes that have increased to such huge proportions that they are hard to work with. Class of diseases • Object Oriented Abuses Incomplete or incorrect application of object-oriented programming principles. • Change Obstacles If you need to change something in one place in your code, you have to make many changes in other places too. • Redundancies Some pointless and unneeded codes whose absence would make the code cleaner, more efficient and easier to understand. • Couplings Excessive coupling between classes.
  • 19. 12/23/2017 Refactoring 19 Bloaters • Long Methods • Large Classes • Primitive Obsession • Long Parameter List • Data Clumps
  • 20. 12/23/2017 Refactoring 20 Long Method Bloaters • A method contains too many lines of code. • Generally, any method longer than ten lines should make you start asking questions. • If you feel need to comment something in a method, write a method instead. Signs Reason Treatment • Since it is easier to write code than to read it, this "smell" remains unnoticed until the method turns into an ugly. • Extract Method, Replace Temp with Query, Introduce Parameter Object. • Preserve Whole Object, Replace Method with Method Object. • Decompose Conditional.
  • 21. 12/23/2017 Refactoring 21 Large Class Bloaters • A class contains many fields/methods/lines of code.Signs Reason Treatment • Programmers usually find it mentally less taxing to place a new feature in an existing class than to create a new class for the feature. • Class has several responsibilities. • Extract Class • Extract Subclass • Extract Interface • Duplicate Observed Data
  • 22. 12/23/2017 Refactoring 22 Primitive Obsession Bloaters • Use of primitives instead of small objects for simple tasks. • Use of constants for coding information. • Use of string constants as field names for use in data arrays. Signs Reason Treatment • "Just a field for storing some data!" the programmer said. • Creating a primitive field is so much easier than making a whole new class, • Replace Data Value with Object. • Introduce Parameter Object, Preserve Whole Object. • Replace Type Code with Class, Replace Type Code with Subclasses or Replace Type Code with State/Strategy. • Replace Array with Object.
  • 23. 12/23/2017 Refactoring 23 Long Parameter List Bloaters • More than three or four parameters for a method.Signs Reason Treatment • A long list of parameters might happen after several types of algorithms are merged in a single method. • Replace Parameter with Method Call. • Preserve Whole Object. • Introduce Parameter Object.
  • 24. 12/23/2017 Refactoring 24 Bloaters • Sometimes different parts of the code contain identical groups of variables. Signs Reason Treatment • Often these data groups are due to poor program structure or "copy-paste programming”. • Just delete one of the data values and see whether the other values still make sense. If this is not the case, this is a good sign that this group of variables should be combined into an object. • Extract Class • Introduce Parameter Object • Preserve Whole Object Data Clumps
  • 25. 12/23/2017 Refactoring 25 OO Abuses • Switch Statements • Temporary Field • Refused Bequest • Alternative Classes with Different Interfaces
  • 26. 12/23/2017 Refactoring 26 OOAbuses • You have a complex switch operator or sequence of if statements. Signs Reason Treatment • Often code for a single switch can be scattered in different places in the program. When a new condition is added, you have to find all the switch code and modify it. • when you see switch you should think of polymorphism. • Extract Method, Move Method. • Replace Type Code with Subclasses • Replace Type Code with State/Strategy. • Replace Conditional with Polymorphism. • Replace Parameter with Explicit Methods. • Introduce Null Object. Switch Statements
  • 27. 12/23/2017 Refactoring 27 OOAbuses • Temporary fields get their values only under certain circumstances. Outside of these circumstances, they are empty. Signs Reason Treatment • Oftentimes, temporary fields are created for use in an algorithm that requires a large amount of inputs. • These fields are used only in the algorithm and go unused the rest of the time. • Extract Class. • Replace Method with Method Object. • Introduce Null Object Temporary Field
  • 28. 12/23/2017 Refactoring 28 OOAbuses • If a subclass uses only some of the methods and properties inherited from its parents, the hierarchy is off-kilter. Signs Reason Treatment • Someone was motivated to create inheritance between classes only by the desire to reuse the code in a superclass. But the superclass and subclass are completely different. • Replace Inheritance with Delegation. • Extract Superclass Refused Bequest
  • 29. 12/23/2017 Refactoring 29 OOAbuses • Two classes perform identical functions but have different method names. Signs Reason Treatment • The programmer who created one of the classes probably didn't know that a functionally equivalent class already existed. • Rename Method • Move Method, Add Parameter • Parameterize Method. • Extract Superclass. Alternative Classes with Different Interfaces
  • 30. 12/23/2017 Refactoring 30 Change Obstacles • Divergent Change • Shotgun Surgery • Parallel Inheritance Hierarchies
  • 31. 12/23/2017 Refactoring 31 ChangeObst • You find yourself having to change many unrelated methods when you make changes to a class. Signs Reason Treatment • Often these divergent modifications are due to poor program structure or "copy-paste programming”. • Extract Class. • Extract Superclass • Extract Subclass Divergent Change
  • 32. 12/23/2017 Refactoring 32 ChangeObst • Making any modifications requires that you make many small changes to many different classes. Signs Reason Treatment • A single responsibility has been split up among a large number of classes. • Move Method • Move Field • Inline Class Shotgun Surgery
  • 33. 12/23/2017 Refactoring 33 ChangeObst • Whenever you create a subclass for a class, you find yourself needing to create a subclass for another class. Signs Reason Treatment • All was well as long as the hierarchy stayed small. But with new classes being added, making changes has become harder and harder. • Move Method • Move Field. Parallel Inheritance Hierarchies
  • 34. 12/23/2017 Refactoring 34 Redundancies • Comments • Data Class • Lazy Class • Duplicate Code • Dead Code • Speculative Generality
  • 35. 12/23/2017 Refactoring 35 Redundancies • A method is filled with explanatory comments.Signs Reason Treatment • If you feel that a code fragment cannot be understood without comments, try to change the code structure in a way that makes comments unnecessary. • The best comment is a good name for a method or class. • Extract Variable. • Extract Method. • Rename Method • Introduce Assertion. Comments
  • 36. 12/23/2017 Refactoring 36 Redundancies • Two code fragments look almost identical.Signs Reason Treatment • Duplication usually occurs when multiple programmers are working on different parts of the same program at the same time. • Extract Method, Pull Up Field • Pull Up Constructor Body. • Form Template Method. • Substitute Algorithm • Extract Superclass, Extract Class • Consolidate Conditional Expression • Consolidate Duplicate Conditional Fragments. Duplicate Code
  • 37. 12/23/2017 Refactoring 37 Redundancies • So if a class doesn't do enough to earn your attention, it should be deleted. Signs Reason Treatment • Perhaps a class was designed to be fully functional but after some of the refactoring it has become small. • Inline Class • Collapse Hierarchy Lazy Class
  • 38. 12/23/2017 Refactoring 38 Redundancies • A data class refers to a class that contains only fields and crude methods for accessing them (getters and setters). Signs Reason Treatment • But the true power of objects is that they can contain behavior types or operations on their data. • Encapsulate Field • Encapsulate Collection • Move Method, Extract Method • Remove Setting Method, Hide Method Data Class
  • 39. 12/23/2017 Refactoring 39 Redundancies • A variable, parameter, field, method or class is no longer used. Signs Reason Treatment • When requirements for the software have changed or corrections have been made, nobody had time to clean up the old code. • Using IDE. • Inline Class, Collapse Hierarchy • Remove Parameter Dead Code
  • 40. 12/23/2017 Refactoring 40 Redundancies • There is an unused class, method, field or parameter.Signs Reason Treatment • Sometimes code is created "just in case" to support anticipated future features that never get implemented. • Collapse Hierarchy. • Inline Class. • Inline Method • Remove Parameter. Speculative Generality
  • 41. 12/23/2017 Refactoring 41 Couplings • Feature Envy • Incomplete Library Class • Middle Man • Inappropriate Intimacy • Message Chains
  • 42. 12/23/2017 Refactoring 42 Couplings • A method accesses the data of another object more than its own data. Signs Reason Treatment • This smell may occur after fields are moved to a data class. If this is the case, you may want to move the operations on data to this class as well. • Move Method • Extract Method Feature Envy
  • 43. 12/23/2017 Refactoring 43 • One class uses the internal fields and methods of another class. Signs Reason Treatment • Keep a close eye on classes that spend too much time together. • Good classes should know as little about each other as possible. • Move Method, Move Field • Extract Class, Hide Delegate • Change Bidirectional Association to Unidirectional. • Replace Delegation with Inheritance. Inappropriate Intimacy Couplings
  • 44. 12/23/2017 Refactoring 44 • In code you see a series of calls resembling $a->b()->c()->d()Signs Reason Treatment • A message chain occurs when a client requests another object, that object requests yet another one, and so on. • These chains mean that the client is dependent on navigation along the class structure • Hide Delegate. • Extract Method • Move Method. Message Chains Couplings
  • 45. 12/23/2017 Refactoring 45 • If a class performs only one action, delegating work to another class, why does it exist at all? Signs Reason Treatment • In other cases, it can be the result of the useful work of a class being gradually moved to other classes. • The class remains as an empty shell that does not do anything other than delegate. • Remove Middle Man Middle Man Couplings
  • 46. 12/23/2017 Refactoring 46 Thanks For your attentions