SlideShare a Scribd company logo
1 of 33
Download to read offline
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

More Related Content

Viewers also liked

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
 

Viewers also liked (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
 

Similar to Bad Smells in Code: Long Method, Duplicated Code & More

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
 

Similar to Bad Smells in Code: Long Method, Duplicated Code & More (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)
 

More from 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
 

More from 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
 

Recently uploaded

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Recently uploaded (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Bad Smells in Code: Long Method, Duplicated Code & More

  • 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