Refactoring
The art of improving the design of existing code
TDD
circle of life
Test fails
Testpasses
Refactor
What is refactoring?
✤ Refactoring does not include just any changes in a system
(features)
✤ Refactoring is not rewriting from scratch
✤ Refactoring is not just any restructuring intended to improve
code
✤ Refactoring changes the balance point between up-front design
and emergent design
✤ Refactoring can be small or large
OK, we want to refactor! But…
✤ Why to refactor?
✤ What to refactor?
✤ How to refactor?
Why?
Because refactored code is easier
to understand and cheaper to
modify
✤ Clean code
✤ Better code
What?
How can we identify the candidate code to refactor?
Intuition?
We need better tools than intuition…
=> We can relay on design smells
How?
Ok, candidate code has been identified
How to improve that code?
Intuition?
No, we need proven tools to improve that code
=> We can relay on refactoring
Design smells
Smells are problems
Smells are warning signs about potential problems in
code
A design smell is a symptom
Smells are violation of principles: SOLID principles
Symptoms
of rotting design
Symptoms of rotting design (1/7)
Rigidity
Software tends to be difficult to change
Symptoms of rotting design (2/7)
Fragility
Software tends to break whenever changes are made
Symptoms of rotting design (3/7)
Viscosity
It is harder to make changes using methods that
preserve design, and easier to use methods that does not
preserve design, such as hacks
Symptoms of rotting design (4/7)
Immobility
It is difficult to reuse software parts
Symptoms of rotting design (5/7)
Needless complexity
Overdesign
Symptoms of rotting design (6/7)
Needless repetition
Cut & paste, updating structures that could be unified
under a single abstraction, DRY
Symptoms of rotting design (7/7)
Opacity
Software tends to be difficult to understand code written
in a clear and expressive manner vs code that is written
in a opaque and convolute manner
Refactoring
circle
While smells remain:
1. Choose the worst smell
2. Select a refactoring that
will address the smell
3. Apply the refactoring
Choose worst sm
ell
Selectrefactoring
Apply refactor
Design smells taxonomy
✤ Bloaters
✤ Object-Orientation Abusers
✤ Change Preventers
✤ Dispensables
✤ Couplers
Bloaters
Bloaters are code, methods and classes
that have increased to such gargantuan
proportions that they are hard to work
with. Usually these smells do not crop up
right away, rather they accumulate over
time as the program evolves (and
especially when nobody makes an effort
to eradicate them).
Bloaters
✤ Long method
✤ Large class
✤ Long parameter list
✤ Primitive obsession
✤ Data clumps
Long method
A method contains too many lines of code. Generally,
any method longer than ten lines should make you start
asking questions
Large class
A class contains many fields/methods/lines of code
Long parameter list
More than three or four parameters for a method.
Primitive obsession
✤ Use of primitives instead of small objects for simple
tasks (such as currency, ranges, special strings for
phone numbers, etc.)
✤ Use of constants for coding information (such as a
constant USER_ADMIN_ROLE = 1 for referring to
users with administrator rights.)
✤ Use of string constants as field names for use in data
arrays.
Data clumps
Sometimes different parts of the code contain identical
groups of variables (such as parameters for connecting to
a database). These clumps should be turned into their
own classes
Object-
Orientation
Abusers
All these smells are incomplete or
incorrect application of object-oriented
programming principles.
Object-Orientation Abusers
✤ Switch statements
✤ Refused bequest
✤ Temporary field
✤ Alternative classes with different interfaces
Switch statements
You have a complex switch operator or sequence of if
statements.
Refused bequest
If a subclass uses only some of the methods and
properties inherited from its parents, the hierarchy is off-
kilter. The unneeded methods may simply go unused or
be redefined and give off exceptions
Temporary field
Temporary fields get their values (and thus are needed
by objects) only under certain circumstances. Outside of
these circumstances, they are empty
Alternative classes with different
interface
Two classes perform identical functions but have
different method names
Change
preventers
These smells mean that if you need to
change something in one place in your
code, you have to make many changes in
other places too. Program development
becomes much more complicated and
expensive as a result
Change preventers
✤ Divergent change
✤ Parallel inheritance hierarchies
✤ Shotgun surgery
Divergent change
You find yourself having to change many unrelated
methods when you make changes to a class. For
example, when adding a new product type you have to
change the methods for finding, displaying, and
ordering products
Parallel inheritance hierarchies
Whenever you create a subclass for a class, you find
yourself needing to create a subclass for another class.
Shotgun surgery
Making any modifications requires that you make many
small changes to many different classes.
Dispensables
A dispensable is something pointless and
unneeded whose absence would make the
code cleaner, more efficient and easier to
understand
Dispensables
✤ Comments
✤ Duplicate code
✤ Lazy class
✤ Data class
✤ Dead code
✤ Speculative generality
Comments
A method is filled with explanatory comment
Duplicated code
Two code fragments look almost identical
Lazy class
Understanding and maintaining classes always costs
time and money. So if a class doesn't do enough to earn
your attention, it should be deleted
Data class
A data class refers to a class that contains only fields and
crude methods for accessing them (getters and setters).
These are simply containers for data used by other
classes. These classes do not contain any additional
functionality and cannot independently operate on the
data that they own.
Dead code
A variable, parameter, field, method or class is no longer
used (usually because it is obsolete)
Speculative generality
There is an unused class, method, field or parameter
Couplers
All the smells in this group contribute to
excessive coupling between classes or
show what happens if coupling is
replaced by excessive delegation
Couplers
✤ Feature envy
✤ Inappropriate intimacy
✤ Message chains
✤ Middle man
✤ Incomplete library class
Feature envy
A method accesses the data of another object more than
its own data
Inappropriate intimacy
One class uses the internal fields and methods of another
class.
Message chains
In code you see a series of calls resembling:
$a->b()->c()->d()
Middle man
If a class performs only one action, delegating work to
another class, why does it exist at all?
Incomplete library class
Sooner or later, libraries stop meeting user needs. The
only solution to the problem – changing the library – is
often impossible since the library is read-only
Questions?
Bibliography:
http://es.slideshare.net/sgganesh/refactoring-for-design-smells
http://es.slideshare.net/gvespucci/design-smells
M. Fowler, Refactoring: Improving the Design of Existing Code, Canada: Addison-Wesley, 2000
W.C. Wake, Refactoring Workbook, Addison Wesley, 2003
https://www.refactoring.com/catalog/
https://sourcemaking.com/refactoring/smells
https://blog.codinghorror.com/code-smells/
http://mikamantyla.eu/BadCodeSmellsTaxonomy.html
http://www.designsmells.com/resources/
https://codurance.com/publications/tag/code-smells/
http://www.xp123.com/rwb/
http://www.industriallogic.com/wp-content/uploads/2005/09/smellstorefactorings.pdf
Images:
https://commons.wikimedia.org/wiki/File:Human_evolution.svg
https://pixabay.com/p-148357/?no_redirect
Zankiu!

Refactoring

  • 1.
    Refactoring The art ofimproving the design of existing code
  • 2.
    TDD circle of life Testfails Testpasses Refactor
  • 3.
    What is refactoring? ✤Refactoring does not include just any changes in a system (features) ✤ Refactoring is not rewriting from scratch ✤ Refactoring is not just any restructuring intended to improve code ✤ Refactoring changes the balance point between up-front design and emergent design ✤ Refactoring can be small or large
  • 4.
    OK, we wantto refactor! But… ✤ Why to refactor? ✤ What to refactor? ✤ How to refactor?
  • 5.
    Why? Because refactored codeis easier to understand and cheaper to modify ✤ Clean code ✤ Better code
  • 6.
    What? How can weidentify the candidate code to refactor? Intuition? We need better tools than intuition… => We can relay on design smells
  • 7.
    How? Ok, candidate codehas been identified How to improve that code? Intuition? No, we need proven tools to improve that code => We can relay on refactoring
  • 8.
    Design smells Smells areproblems Smells are warning signs about potential problems in code A design smell is a symptom Smells are violation of principles: SOLID principles
  • 9.
  • 10.
    Symptoms of rottingdesign (1/7) Rigidity Software tends to be difficult to change
  • 11.
    Symptoms of rottingdesign (2/7) Fragility Software tends to break whenever changes are made
  • 12.
    Symptoms of rottingdesign (3/7) Viscosity It is harder to make changes using methods that preserve design, and easier to use methods that does not preserve design, such as hacks
  • 13.
    Symptoms of rottingdesign (4/7) Immobility It is difficult to reuse software parts
  • 14.
    Symptoms of rottingdesign (5/7) Needless complexity Overdesign
  • 15.
    Symptoms of rottingdesign (6/7) Needless repetition Cut & paste, updating structures that could be unified under a single abstraction, DRY
  • 16.
    Symptoms of rottingdesign (7/7) Opacity Software tends to be difficult to understand code written in a clear and expressive manner vs code that is written in a opaque and convolute manner
  • 17.
    Refactoring circle While smells remain: 1.Choose the worst smell 2. Select a refactoring that will address the smell 3. Apply the refactoring Choose worst sm ell Selectrefactoring Apply refactor
  • 18.
    Design smells taxonomy ✤Bloaters ✤ Object-Orientation Abusers ✤ Change Preventers ✤ Dispensables ✤ Couplers
  • 19.
    Bloaters Bloaters are code,methods and classes that have increased to such gargantuan proportions that they are hard to work with. Usually these smells do not crop up right away, rather they accumulate over time as the program evolves (and especially when nobody makes an effort to eradicate them).
  • 20.
    Bloaters ✤ Long method ✤Large class ✤ Long parameter list ✤ Primitive obsession ✤ Data clumps
  • 21.
    Long method A methodcontains too many lines of code. Generally, any method longer than ten lines should make you start asking questions
  • 22.
    Large class A classcontains many fields/methods/lines of code
  • 23.
    Long parameter list Morethan three or four parameters for a method.
  • 24.
    Primitive obsession ✤ Useof primitives instead of small objects for simple tasks (such as currency, ranges, special strings for phone numbers, etc.) ✤ Use of constants for coding information (such as a constant USER_ADMIN_ROLE = 1 for referring to users with administrator rights.) ✤ Use of string constants as field names for use in data arrays.
  • 25.
    Data clumps Sometimes differentparts of the code contain identical groups of variables (such as parameters for connecting to a database). These clumps should be turned into their own classes
  • 26.
    Object- Orientation Abusers All these smellsare incomplete or incorrect application of object-oriented programming principles.
  • 27.
    Object-Orientation Abusers ✤ Switchstatements ✤ Refused bequest ✤ Temporary field ✤ Alternative classes with different interfaces
  • 28.
    Switch statements You havea complex switch operator or sequence of if statements.
  • 29.
    Refused bequest If asubclass uses only some of the methods and properties inherited from its parents, the hierarchy is off- kilter. The unneeded methods may simply go unused or be redefined and give off exceptions
  • 30.
    Temporary field Temporary fieldsget their values (and thus are needed by objects) only under certain circumstances. Outside of these circumstances, they are empty
  • 31.
    Alternative classes withdifferent interface Two classes perform identical functions but have different method names
  • 32.
    Change preventers These smells meanthat if you need to change something in one place in your code, you have to make many changes in other places too. Program development becomes much more complicated and expensive as a result
  • 33.
    Change preventers ✤ Divergentchange ✤ Parallel inheritance hierarchies ✤ Shotgun surgery
  • 34.
    Divergent change You findyourself having to change many unrelated methods when you make changes to a class. For example, when adding a new product type you have to change the methods for finding, displaying, and ordering products
  • 35.
    Parallel inheritance hierarchies Wheneveryou create a subclass for a class, you find yourself needing to create a subclass for another class.
  • 36.
    Shotgun surgery Making anymodifications requires that you make many small changes to many different classes.
  • 37.
    Dispensables A dispensable issomething pointless and unneeded whose absence would make the code cleaner, more efficient and easier to understand
  • 38.
    Dispensables ✤ Comments ✤ Duplicatecode ✤ Lazy class ✤ Data class ✤ Dead code ✤ Speculative generality
  • 39.
    Comments A method isfilled with explanatory comment
  • 40.
    Duplicated code Two codefragments look almost identical
  • 41.
    Lazy class Understanding andmaintaining classes always costs time and money. So if a class doesn't do enough to earn your attention, it should be deleted
  • 42.
    Data class A dataclass refers to a class that contains only fields and crude methods for accessing them (getters and setters). These are simply containers for data used by other classes. These classes do not contain any additional functionality and cannot independently operate on the data that they own.
  • 43.
    Dead code A variable,parameter, field, method or class is no longer used (usually because it is obsolete)
  • 44.
    Speculative generality There isan unused class, method, field or parameter
  • 45.
    Couplers All the smellsin this group contribute to excessive coupling between classes or show what happens if coupling is replaced by excessive delegation
  • 46.
    Couplers ✤ Feature envy ✤Inappropriate intimacy ✤ Message chains ✤ Middle man ✤ Incomplete library class
  • 47.
    Feature envy A methodaccesses the data of another object more than its own data
  • 48.
    Inappropriate intimacy One classuses the internal fields and methods of another class.
  • 49.
    Message chains In codeyou see a series of calls resembling: $a->b()->c()->d()
  • 50.
    Middle man If aclass performs only one action, delegating work to another class, why does it exist at all?
  • 51.
    Incomplete library class Sooneror later, libraries stop meeting user needs. The only solution to the problem – changing the library – is often impossible since the library is read-only
  • 52.
  • 53.
    Bibliography: http://es.slideshare.net/sgganesh/refactoring-for-design-smells http://es.slideshare.net/gvespucci/design-smells M. Fowler, Refactoring:Improving the Design of Existing Code, Canada: Addison-Wesley, 2000 W.C. Wake, Refactoring Workbook, Addison Wesley, 2003 https://www.refactoring.com/catalog/ https://sourcemaking.com/refactoring/smells https://blog.codinghorror.com/code-smells/ http://mikamantyla.eu/BadCodeSmellsTaxonomy.html http://www.designsmells.com/resources/ https://codurance.com/publications/tag/code-smells/ http://www.xp123.com/rwb/ http://www.industriallogic.com/wp-content/uploads/2005/09/smellstorefactorings.pdf Images: https://commons.wikimedia.org/wiki/File:Human_evolution.svg https://pixabay.com/p-148357/?no_redirect
  • 54.