SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Bad Smells in Code
Will Shen
2013/03/14
Reference
Martin Fowler, “Refactoring - Improving the
Design of Existing Code”, Addison Wesley,
1999.
2
Outline
Defining Refactoring
Bad Smells in Code
Reading Schedule
3
Defining Refactoring
Refactoring (noun)
• a change made to the internal structure of
software to make it easier to understand and
cheaper to modify without changing its
observable behavior.
Refactor (verb)
• to restructure software by applying a series of
refactorings without changing its observable
behavior
4
Why Should You Refactor?
To improve the design of software
To make software easier to understand
• Somebody else will eventually have to read your
code
To help you find bugs
To help you program faster
5
When to do Refactoring
1. Refactor when you add function
• Helps you to understand the code you are modifying
• Sometimes the existing design does not allow you to easily
add the feature
2. Refactor when you need to fix a bug
• the code was not clear enough for you to see the bug in
the first place
3. Refactor as you do a code review
• Code reviews help spread knowledge through the
development team
6
The Rule of three - Three strikes and you refactor
1. The first time you do something, you just do
it.
2. The second time you do something similar,
you wince at the duplication, but you do the
duplicate thing anyway.
3. The third time you do something similar, you
refactor.
7
DRY Principle
8
DO NOT
TOUCH
REPEAT
YOURSELF
Refactoring and Design
Refactoring changes the role of upfront
design
•  Code the first approach you discover
 get it working
 refactor it into shape
A reasonable solution > looking for the
perfect solution
Refactoring can lead to simpler designs
without sacrificing flexibility
9
Refactoring and Unit Tests
Refactoring is strongly dependent on
having a good suite of unit tests
• To verify that the behavior is indeed preserved
Without unit tests  the fear that
something may break.
10
Red/Green/Refactor
11
Bad Smells in Code
12
Bad Smells in Code
Duplicated Code
Long Method
Large Class
Long Parameter List
Divergent Change
Shotgun Surgery
Feature Envy
Data Clumps
Primitive Obsession
Switch Statements
Parallel Inheritance
Hierarchies
Lazy Class
Speculative
Generality
Temporary Field
Message Chains
Middle Man
Inappropriate
Intimacy
Alternative Classes
with Different
Interfaces
Incomplete Library
Class
Data Class
13
Duplicated Code
Code that is the
same, or performs
the same function
are showing up in
multiple places
within a program
Having the same
expression in two
methods of the same
class  Extract
Method
Having the same
expression in two
sibling subclasses 
Extract Method + Pull
Up Field
Having duplicated
code in two unrelated
classes  Extract
Class
14
Long Method
A lack of proper
encapsulation
It does too much
itself, and doesn't
delegate that work to
the proper
authorities
Prevent code reuse
To shorten a method
 Extract Method
Passing a lot of
parameters 
Replace Temp with
Query
Sliming down the
long list of
parameters 
Introduce Parameter
Object, Preserve
Whole Object
15
Large Class
A class has taken on
too much
responsibilities.
• Complexity - hard to
understand.
• Bloat - take longer to
understand.
A class doing too
much  too many
instance variables
duplicated code!
Extract Class +
Extract Subclass
16
Long Parameter List
The method is doing
too much - why does
it need all of that
information?
Understandability -
lots of parameters
will make code
harder to
understand.
difficult to use
changing them needs
more data
Replace Parameter
with Method when
you can get the data
in one parameter 
making a request of
an object
17
Divergent Change
One class is commonly changed in different
ways for different reasons
To clean this up you identify everything that
changes for a particular cause and use Extract
Class to put them all together
18
Shotgun Surgery
Make a kind of
change  have to
make a lot of little
changes to a lot of
different classes
Changes are hard to
find
Easy to miss an
important change.
Move Method and
Move Field to put all
the changes in a
single class
If no current class
looks like a good
candidate then create
one – Extract Class
Inline Class to bring
a whole bunch of
behavior together
19
Feature Envy
A method seems more interested in
another class
The method clearly wants to be
elsewhere  Move Method
Only part of the method  Extract
Method +Move Method
20
Data Clumps
See the same three or four data items together
in lots of places:
• Fields in a couple of classes
• Parameters in many method signatures
Use Extract Class to turn the clumps into an
object
For method parameters use Introduce
Parameter Object or Preserve Whole Object to
slim them down
21
Primitive Obsession
Using primitive data
types and method calls to
generate desired
outcomes, and could be
written in a more
descriptive and
sustainable way.
People new to objects are
sometimes reluctant to
use small objects for
small tasks
Replace Data Value with
Object on individual data
values
Replace Type Code with
Class if the value does not
effect the behavior
Have conditional that
depend on the type code 
Replace Type Code with
Subclass or Replace Type
Code with State/Strategy
22
Switch Statements
See a switch statement  polymorphism
Extract Method + Move Method
Only have a few case that effect a single
method then polymorphism is overkill 
Replace Parameter with Explicit Methods
One of the conditional cases is null 
Introduce Null Object
23
Parallel Inheritance Hierarchies
Make a subclass of one class  you have to
make a subclass of another (this is a special
case of shotgun surgery)
To make sure that instances of one hierarchy
refer to instance of another
Move Method + Move Field  the hierarchy on
the referring class disappears
24
Lazy Class
A class that is not
carrying its weight
should be eliminated
• Each class you create
costs money and time to
maintain and understand
Subclasses that are
not doing enough 
Collapse Hierarchy
Nearly useless
components  Inline
Class
25
Speculative Generality
Creating today what we
speculate will be needed
in the future
• the only users of a class or
method are test cases
Abstract classes that are
not doing enough 
Collapse Hierarchy
Unnecessary delegation
 Inline Class
Methods with unused
parameters should 
Remove Parameter
Methods named with odd
abstract names 
Rename Method
26
Temporary Field
See an object in
which an instance
variable is set only in
certain
circumstances
difficult to
understand because
we usually expect an
object to use all of its
variables
Use Extract Class to
create a home for
orphan variables
Eliminate conditional
code by using
Introduce Null Object
to create an
alternative
component for when
the variables are not
valid
27
Message Chains
AGetB()GetC()…DoSomething()
Hide Delegate at various points in the
chain
28
Middle Man
Encapsulation  often comes with delegation 
sometimes delegation can go to far
Half the methods are delegated to another class 
Remove Middle Man and talk to the object that really
knows what is going on
A few methods are not doing much  Inline Method
If there is additional behavior  Replace Delegation
with Inheritance to turn the middle man into a subclass
of the real object
29
Inappropriate Intimacy
Sometimes classes
become far too
intimate and spend
too much time in
each other's private
parts
Use Move Method and
Move Field to separate
the pieces to reduce the
intimacy
If the classes do have
common interests
• Extract Class to put the
commonality in a safe place
• Hide Delegate to let another
class act as a go-between
Change Bidirectional
Association to
Unidirectional
30
Alternative Classes with Different Interfaces
use Rename Method on any methods that do
the same thing but have different signatures
for what they do
Keep using Move Method to move behavior to
other classes until the protocols are the same
If you have to redundantly move code to
accomplish this, you may be able to use
Extract Superclass
31
Incomplete Library Class
The library is
insufficient for
your needs
If there are just a
couple of methods
that you wish the
library class had 
Introduce Foreign
Method
If there is more extra
behavior you need 
Introduce Local
Extension
32
Data Class
Classes that have fields,
getting and setting
methods, and nothing
else
Dumb data holders
Manipulated in far too
much detail by other
classes
public fields 
Encapsulate Field
A collection of fields 
Encapsulate Collection
Remove Setting Method
on any field that should
not be changed
Move Method to move
behavior into the data
class
If you can't move a whole
method, use Extract
Method to create a
method that can be
moved
33

Contenu connexe

En vedette

Astronomy libraries - your gateway to information
Astronomy libraries - your gateway to informationAstronomy libraries - your gateway to information
Astronomy libraries - your gateway to informationUta Grothkopf
 
Facebook apps
Facebook apps Facebook apps
Facebook apps PRDESQ
 
Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija
Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija
Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija Aurimas Baltušis
 
De nieuwe Aanbestedingswet en de Gids Proportionaliteit
De nieuwe Aanbestedingswet en de Gids ProportionaliteitDe nieuwe Aanbestedingswet en de Gids Proportionaliteit
De nieuwe Aanbestedingswet en de Gids ProportionaliteitAKD
 
T H E S E E D S O F H A P P I N E S S D R
T H E  S E E D S  O F  H A P P I N E S S  D RT H E  S E E D S  O F  H A P P I N E S S  D R
T H E S E E D S O F H A P P I N E S S D Rasawarik
 
Vector Graphics W4
Vector Graphics W4Vector Graphics W4
Vector Graphics W4twmffat
 
Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014
Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014
Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014QSRC NITA Dongguk
 
Military TBI Post ; Special Focus on Military Women
Military TBI Post ; Special Focus on Military WomenMilitary TBI Post ; Special Focus on Military Women
Military TBI Post ; Special Focus on Military Womenjenifur1106
 
BCMG 7 13 09 Generic Pp Pics
BCMG 7 13 09 Generic Pp PicsBCMG 7 13 09 Generic Pp Pics
BCMG 7 13 09 Generic Pp Picsegoldman
 
Wagner College Forum for Undergraduate Research, Vol 12 No 1
Wagner College Forum for Undergraduate Research, Vol 12 No 1Wagner College Forum for Undergraduate Research, Vol 12 No 1
Wagner College Forum for Undergraduate Research, Vol 12 No 1Wagner College
 
Short film distribution ( version 2 )
Short film distribution ( version 2 ) Short film distribution ( version 2 )
Short film distribution ( version 2 ) Amber2805
 

En vedette (15)

Anand Jha-Updated CV
Anand Jha-Updated CVAnand Jha-Updated CV
Anand Jha-Updated CV
 
QSAR inquiries, LLC
QSAR inquiries, LLCQSAR inquiries, LLC
QSAR inquiries, LLC
 
Astronomy libraries - your gateway to information
Astronomy libraries - your gateway to informationAstronomy libraries - your gateway to information
Astronomy libraries - your gateway to information
 
Facebook apps
Facebook apps Facebook apps
Facebook apps
 
Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija
Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija
Lietuvos pieno perdirbėjų asociacijos „Pieno centras“ spaudos konferencija
 
De nieuwe Aanbestedingswet en de Gids Proportionaliteit
De nieuwe Aanbestedingswet en de Gids ProportionaliteitDe nieuwe Aanbestedingswet en de Gids Proportionaliteit
De nieuwe Aanbestedingswet en de Gids Proportionaliteit
 
T H E S E E D S O F H A P P I N E S S D R
T H E  S E E D S  O F  H A P P I N E S S  D RT H E  S E E D S  O F  H A P P I N E S S  D R
T H E S E E D S O F H A P P I N E S S D R
 
Responsiv Design, WordCampCPH 14
Responsiv Design, WordCampCPH 14Responsiv Design, WordCampCPH 14
Responsiv Design, WordCampCPH 14
 
Vector Graphics W4
Vector Graphics W4Vector Graphics W4
Vector Graphics W4
 
Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014
Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014
Beautiful Mang-Sang Beach and Seol-Ak-San 20-21 July 2014
 
Military TBI Post ; Special Focus on Military Women
Military TBI Post ; Special Focus on Military WomenMilitary TBI Post ; Special Focus on Military Women
Military TBI Post ; Special Focus on Military Women
 
BCMG 7 13 09 Generic Pp Pics
BCMG 7 13 09 Generic Pp PicsBCMG 7 13 09 Generic Pp Pics
BCMG 7 13 09 Generic Pp Pics
 
Wagner College Forum for Undergraduate Research, Vol 12 No 1
Wagner College Forum for Undergraduate Research, Vol 12 No 1Wagner College Forum for Undergraduate Research, Vol 12 No 1
Wagner College Forum for Undergraduate Research, Vol 12 No 1
 
Short film distribution ( version 2 )
Short film distribution ( version 2 ) Short film distribution ( version 2 )
Short film distribution ( version 2 )
 
compplanoverview_us_en
compplanoverview_us_encompplanoverview_us_en
compplanoverview_us_en
 

Similaire à Bade Smells in Code

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 codeValerio Maggio
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문Sangcheol Hwang
 
Speeding up web_application
Speeding up web_applicationSpeeding up web_application
Speeding up web_applicationAchintya Kumar
 
Code Refactoring using rails
Code Refactoring using railsCode Refactoring using rails
Code Refactoring using railsAchintya Kumar
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - RefactoringDiaa Al-Salehi
 
Design Patterns .Net
Design Patterns .NetDesign Patterns .Net
Design Patterns .NetHariom Shah
 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
 
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Justin Gordon
 
Introduction to AntiPatterns & CodeSmells
Introduction to AntiPatterns & CodeSmellsIntroduction to AntiPatterns & CodeSmells
Introduction to AntiPatterns & CodeSmellsClaudio Bernasconi
 
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
 

Similaire à Bade Smells in Code (20)

Code Refactoring
Code RefactoringCode Refactoring
Code 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
 
Refactoring
RefactoringRefactoring
Refactoring
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
 
Bad Smells in Code
Bad Smells in CodeBad Smells in Code
Bad Smells in Code
 
Code smells
Code smellsCode smells
Code smells
 
Speeding up web_application
Speeding up web_applicationSpeeding up web_application
Speeding up web_application
 
Code Refactoring using rails
Code Refactoring using railsCode Refactoring using rails
Code Refactoring using rails
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - Refactoring
 
Design Patterns .Net
Design Patterns .NetDesign Patterns .Net
Design Patterns .Net
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
 
Code smells
Code smellsCode smells
Code smells
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
Introduction to AntiPatterns & CodeSmells
Introduction to AntiPatterns & CodeSmellsIntroduction to AntiPatterns & CodeSmells
Introduction to AntiPatterns & CodeSmells
 
C# interview questions
C# interview questionsC# interview questions
C# interview questions
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
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)
 

Plus de Will Shen

20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)Will Shen
 
16格筆記讀書法
16格筆記讀書法16格筆記讀書法
16格筆記讀書法Will Shen
 
Intro To BOOST.Spirit
Intro To BOOST.SpiritIntro To BOOST.Spirit
Intro To BOOST.SpiritWill Shen
 
20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...Will Shen
 
20060411 face recognition using face arg matching
20060411 face recognition using face arg matching20060411 face recognition using face arg matching
20060411 face recognition using face arg matchingWill Shen
 
20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)Will Shen
 
20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testingWill Shen
 
20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysisWill Shen
 
20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State MachineWill Shen
 
Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)Will Shen
 
Junit Recipes - Elementary tests (1/2)
Junit Recipes  - Elementary tests (1/2)Junit Recipes  - Elementary tests (1/2)
Junit Recipes - Elementary tests (1/2)Will Shen
 
Junit Recipes - Intro
Junit Recipes - IntroJunit Recipes - Intro
Junit Recipes - IntroWill Shen
 
20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui softwareWill Shen
 
20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...Will Shen
 
20041221 gui testing survey
20041221 gui testing survey20041221 gui testing survey
20041221 gui testing surveyWill Shen
 
20060927 application facades
20060927 application facades20060927 application facades
20060927 application facadesWill Shen
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Data collection for field studies
Data collection for field studiesData collection for field studies
Data collection for field studiesWill Shen
 

Plus de Will Shen (18)

20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
20180717 Introduction of Seamless BLE Connection Migration System (SeamBlue)
 
16格筆記讀書法
16格筆記讀書法16格筆記讀書法
16格筆記讀書法
 
Intro To BOOST.Spirit
Intro To BOOST.SpiritIntro To BOOST.Spirit
Intro To BOOST.Spirit
 
20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...
 
20060411 face recognition using face arg matching
20060411 face recognition using face arg matching20060411 face recognition using face arg matching
20060411 face recognition using face arg matching
 
20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)20060411 Analytic Hierarchy Process (AHP)
20060411 Analytic Hierarchy Process (AHP)
 
20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing20050713 critical paths for gui regression testing
20050713 critical paths for gui regression testing
 
20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis20050314 specification based regression test selection with risk analysis
20050314 specification based regression test selection with risk analysis
 
20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine20041113 A Test Generation Tool for Specifications in the Form of State Machine
20041113 A Test Generation Tool for Specifications in the Form of State Machine
 
Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)
 
Junit Recipes - Elementary tests (1/2)
Junit Recipes  - Elementary tests (1/2)Junit Recipes  - Elementary tests (1/2)
Junit Recipes - Elementary tests (1/2)
 
Junit Recipes - Intro
Junit Recipes - IntroJunit Recipes - Intro
Junit Recipes - Intro
 
20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software20051019 automating regression testing for evolving gui software
20051019 automating regression testing for evolving gui software
 
20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...20060712 automated model based testing of community-driven open-source gui ap...
20060712 automated model based testing of community-driven open-source gui ap...
 
20041221 gui testing survey
20041221 gui testing survey20041221 gui testing survey
20041221 gui testing survey
 
20060927 application facades
20060927 application facades20060927 application facades
20060927 application facades
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Data collection for field studies
Data collection for field studiesData collection for field studies
Data collection for field studies
 

Dernier

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Dernier (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Bade Smells in Code

  • 1. Bad Smells in Code Will Shen 2013/03/14
  • 2. Reference Martin Fowler, “Refactoring - Improving the Design of Existing Code”, Addison Wesley, 1999. 2
  • 3. Outline Defining Refactoring Bad Smells in Code Reading Schedule 3
  • 4. Defining Refactoring Refactoring (noun) • a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior. Refactor (verb) • to restructure software by applying a series of refactorings without changing its observable behavior 4
  • 5. Why Should You Refactor? To improve the design of software To make software easier to understand • Somebody else will eventually have to read your code To help you find bugs To help you program faster 5
  • 6. When to do Refactoring 1. Refactor when you add function • Helps you to understand the code you are modifying • Sometimes the existing design does not allow you to easily add the feature 2. Refactor when you need to fix a bug • the code was not clear enough for you to see the bug in the first place 3. Refactor as you do a code review • Code reviews help spread knowledge through the development team 6
  • 7. The Rule of three - Three strikes and you refactor 1. The first time you do something, you just do it. 2. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. 3. The third time you do something similar, you refactor. 7
  • 9. Refactoring and Design Refactoring changes the role of upfront design •  Code the first approach you discover  get it working  refactor it into shape A reasonable solution > looking for the perfect solution Refactoring can lead to simpler designs without sacrificing flexibility 9
  • 10. Refactoring and Unit Tests Refactoring is strongly dependent on having a good suite of unit tests • To verify that the behavior is indeed preserved Without unit tests  the fear that something may break. 10
  • 12. Bad Smells in Code 12
  • 13. Bad Smells in Code Duplicated Code Long Method Large Class Long Parameter List Divergent Change Shotgun Surgery Feature Envy Data Clumps Primitive Obsession Switch Statements Parallel Inheritance Hierarchies Lazy Class Speculative Generality Temporary Field Message Chains Middle Man Inappropriate Intimacy Alternative Classes with Different Interfaces Incomplete Library Class Data Class 13
  • 14. Duplicated Code Code that is the same, or performs the same function are showing up in multiple places within a program Having the same expression in two methods of the same class  Extract Method Having the same expression in two sibling subclasses  Extract Method + Pull Up Field Having duplicated code in two unrelated classes  Extract Class 14
  • 15. Long Method A lack of proper encapsulation It does too much itself, and doesn't delegate that work to the proper authorities Prevent code reuse To shorten a method  Extract Method Passing a lot of parameters  Replace Temp with Query Sliming down the long list of parameters  Introduce Parameter Object, Preserve Whole Object 15
  • 16. Large Class A class has taken on too much responsibilities. • Complexity - hard to understand. • Bloat - take longer to understand. A class doing too much  too many instance variables duplicated code! Extract Class + Extract Subclass 16
  • 17. Long Parameter List The method is doing too much - why does it need all of that information? Understandability - lots of parameters will make code harder to understand. difficult to use changing them needs more data Replace Parameter with Method when you can get the data in one parameter  making a request of an object 17
  • 18. Divergent Change One class is commonly changed in different ways for different reasons To clean this up you identify everything that changes for a particular cause and use Extract Class to put them all together 18
  • 19. Shotgun Surgery Make a kind of change  have to make a lot of little changes to a lot of different classes Changes are hard to find Easy to miss an important change. Move Method and Move Field to put all the changes in a single class If no current class looks like a good candidate then create one – Extract Class Inline Class to bring a whole bunch of behavior together 19
  • 20. Feature Envy A method seems more interested in another class The method clearly wants to be elsewhere  Move Method Only part of the method  Extract Method +Move Method 20
  • 21. Data Clumps See the same three or four data items together in lots of places: • Fields in a couple of classes • Parameters in many method signatures Use Extract Class to turn the clumps into an object For method parameters use Introduce Parameter Object or Preserve Whole Object to slim them down 21
  • 22. Primitive Obsession Using primitive data types and method calls to generate desired outcomes, and could be written in a more descriptive and sustainable way. People new to objects are sometimes reluctant to use small objects for small tasks Replace Data Value with Object on individual data values Replace Type Code with Class if the value does not effect the behavior Have conditional that depend on the type code  Replace Type Code with Subclass or Replace Type Code with State/Strategy 22
  • 23. Switch Statements See a switch statement  polymorphism Extract Method + Move Method Only have a few case that effect a single method then polymorphism is overkill  Replace Parameter with Explicit Methods One of the conditional cases is null  Introduce Null Object 23
  • 24. Parallel Inheritance Hierarchies Make a subclass of one class  you have to make a subclass of another (this is a special case of shotgun surgery) To make sure that instances of one hierarchy refer to instance of another Move Method + Move Field  the hierarchy on the referring class disappears 24
  • 25. Lazy Class A class that is not carrying its weight should be eliminated • Each class you create costs money and time to maintain and understand Subclasses that are not doing enough  Collapse Hierarchy Nearly useless components  Inline Class 25
  • 26. Speculative Generality Creating today what we speculate will be needed in the future • the only users of a class or method are test cases Abstract classes that are not doing enough  Collapse Hierarchy Unnecessary delegation  Inline Class Methods with unused parameters should  Remove Parameter Methods named with odd abstract names  Rename Method 26
  • 27. Temporary Field See an object in which an instance variable is set only in certain circumstances difficult to understand because we usually expect an object to use all of its variables Use Extract Class to create a home for orphan variables Eliminate conditional code by using Introduce Null Object to create an alternative component for when the variables are not valid 27
  • 29. Middle Man Encapsulation  often comes with delegation  sometimes delegation can go to far Half the methods are delegated to another class  Remove Middle Man and talk to the object that really knows what is going on A few methods are not doing much  Inline Method If there is additional behavior  Replace Delegation with Inheritance to turn the middle man into a subclass of the real object 29
  • 30. Inappropriate Intimacy Sometimes classes become far too intimate and spend too much time in each other's private parts Use Move Method and Move Field to separate the pieces to reduce the intimacy If the classes do have common interests • Extract Class to put the commonality in a safe place • Hide Delegate to let another class act as a go-between Change Bidirectional Association to Unidirectional 30
  • 31. Alternative Classes with Different Interfaces use Rename Method on any methods that do the same thing but have different signatures for what they do Keep using Move Method to move behavior to other classes until the protocols are the same If you have to redundantly move code to accomplish this, you may be able to use Extract Superclass 31
  • 32. Incomplete Library Class The library is insufficient for your needs If there are just a couple of methods that you wish the library class had  Introduce Foreign Method If there is more extra behavior you need  Introduce Local Extension 32
  • 33. Data Class Classes that have fields, getting and setting methods, and nothing else Dumb data holders Manipulated in far too much detail by other classes public fields  Encapsulate Field A collection of fields  Encapsulate Collection Remove Setting Method on any field that should not be changed Move Method to move behavior into the data class If you can't move a whole method, use Extract Method to create a method that can be moved 33