SlideShare una empresa de Scribd logo
1 de 49
Descargar para leer sin conexión
Bad smell in codes – Part 1
                  If it stinks change it.




Presented By:
Fuad Bin Omar               Rashed Kibria
fuad@code71.com             rashed@code71.com
www.code71.com              www.code71.com
Smells to be covered

    •Duplicated code
    •Long method
    •Long parameter list
    •Divergent change
    •Shotgun surgery
Duplicated Code
Smell
• Same code structure in more than
  one place.

Refactor
Extract method and invoke it from
 both the places.
Extract Method
• You have a code fragment that can
  be grouped together.
• Turn the fragment into a method
  whose name explains the
  purpose of the method.
Extract Method (Contd.)
void printOwing()
{
printBanner();
//print details
System.out.println ("name: " + _name);
System.out.println ("amount " +
  getOutstanding());
}
Extract Method (Contd.)
void printOwing()
{
printBanner();
printDetails(getOutstanding());
}
void printDetails (double outstanding)
{
System.out.println ("name: " + _name);
System.out.println ("amount " +
  outstanding);
}
Duplicated Code
Smell
• same expression in two sibling
  subclasses
Refactor
• Extract method in both classes.
• Pull up field.
Pull Up Field
• Two subclasses have the same field.
• Move the field to the superclass.
Pull Up Field (Contd.)
Duplicated Code
Smell
• Code is similar but not the same
Refactor:
• Use Extract Method to
separate the similar bits from the
  different bits.
• Use Form Template Method.
Form template method
• You have two methods in subclasses
  that perform similar steps in the same
  order, yet the steps are different.
• Get the steps into methods with
  the same signature, so that the
  original methods become the
  same. Then you can pull them up.
Form Template Method
       (Contd.)
Duplicated Code
Smell
• Methods do the same thing with a
  different algorithm
Refactor:
• Choose the clearer of the two
  algorithms Use
• Use Substitute Algorithm.
Substitute Algorithm
• You want to replace an algorithm
  with one that is clearer.
• Replace the body of the method
  with the new algorithm.
Substitute
         Algorithm(Contd.)
String foundPerson(String[] people)
{
for (int i = 0; i < people.length; i++)
{
if (people[i].equals ("Don")){ return "Don"; }
if (people[i].equals ("John")){ return "John"; }
if (people[i].equals ("Kent")){ return "Kent"; }
}
return "";
}
Substitute Algorithm
             (Contd.)
String foundPerson(String[] people)
{
List candidates = Arrays.asList(new String[] {"Don",
  "John", "Kent"});
for (int i=0; i<people.length; i++)
if (candidates.contains(people[i]))
return people[i]; return "";
}
Duplicated Code
Smell
• Duplicated code in two unrelated class.
Refactor:
• Use Extract Class in one class.
• Use the new component to the other.
• Decide where the method makes sense.
Extract Class
• You have one class doing work that
  should be done by two.
• Create a new class and move the
  relevant fields and methods from
  the old class into the new class.
Extract Class (Contd.)
Long method
• Object program having short
  methods live best and longest.
• Little methods are the most valuable.
• Longer methods are difficult to
  understand.
Long method
• Give methods a good name.
• Whenever you feel the need to comment
  something make it a method.
  – Group of lines
  – Even if it is a single line
  – Even if method call is longer than code itself.
  – Method length is not the key here.
  – What the method does and how it does it is
    important.
Long method
• Extract Method
Long method
Smell
Use of temporary variable.
Refactor
Replace temp with query.
Replace temp with query

• You are using a temporary variable
  to hold the result of an expression.
• Extract the expression into a
  method. Replace all references
  to the temp with the expression.
  The new method can then be
  used in other methods
Replace temp with query
double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
Replace temp with query
if (basePrice() > 1000)
return basePrice() * 0.95;
else return basePrice() * 0.98;
 ...
 ...

double basePrice()
{
return _quantity * _itemPrice;
}
Long method
Smell
Methods with long list of parameters.

Refactor
Introduce Parameter Object
Preserve Whole Object
Method with method Object
Introduce Parameter Object

• You have a group of parameters that
  naturally go together.
• Replace them with an object.
Introduce Parameter
       Object
Preserve whole object
• You are getting several values from
  an object and passing these values
  as parameters in a method call.
• Send the whole object instead.
Preserve whole object
int low = daysTempRange().getLow();
int high = daysTempRange().getHigh();
  withinPlan = plan.withinRange(low,
  high);
Preserve whole object
withinPlan =
  plan.withinRange(daysTempRange());
Replace method with
        method object
• You have a long method that uses local
  variables in such a way that you cannot
  apply Extract Method
• Turn the method into its own object
  so that all the local variables become
  fields on that object. You can then
  decompose the method into other
  methods on the same object.
Replace method with
        method object
class Order
{
double price()
{
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation;
}
}
Replace method with
   method object
Long method
Smell
• Too many conditions and loops
Refactor
• With loops, extract the loop and the
  code within the loop into its own
  method.
• Use Decompose Conditional.
Decompose Conditional
• You have a complicated conditional
  (if-then-else) statement.
• Extract methods from the
  condition, then part, and else
  parts
Decompose Conditional
if (date.before (SUMMER_START) || date.after(SUMMER_END))
charge = quantity * _winterRate + _winterServiceCharge;
else
charge = quantity * _summerRate;
Decompose Conditional
if (notSummer(date))
charge = winterCharge(quantity);
else
charge = summerCharge (quantity);
Long Parameter List
Smell
• A method call requires passing long list of
  parameters.


Refactor
• Use Replace Parameter with Method, Preserve
  whole object or Introduce Parameter Object.
Replace Parameter With
          Method
int basePrice = _quantity * _itemPrice;
discountLevel = getDiscountLevel();
double finalPrice =
discountedPrice (basePrice,discountLevel);




int basePrice = _quantity * _itemPrice;
double finalPrice =
discountedPrice(basePrice);
Divergent Change
Smell
• One class is commonly changed in different ways for
  different reasons.


Refactor
• Use Extract class by identifying everything that changes
  for a particular cause and put them all together.
Shotgun Surgery
Smell
• A small changes in the code force changes in different classes.


Refactor
• Use Move Method and Move Field to put all the changes into
  a single class.
• If no current class looks like a good candidate, create one.
• use Inline Class to bring a whole bunch of behavior together.
Move Method

• A method is, or will be, using or used
  by more features of another class
  than the class on which it is defined.
• Create a new method with a
  similar body in the class it uses
  most. Either turn the old method
  into a simple delegation, or
  remove it altogether.
Introduce Parameter
       Object
Move Field

• A field is, or will be, used by another
  class more than the class on which it
  is defined.
• Create a new field in the target
  class, and change all its users.
Introduce Parameter
       Object
To be continued..
References

1. Refactoring: Improving the Design of Existing Code
   By
   Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

2. www.refactoring.com

Más contenido relacionado

La actualidad más candente

The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 Mahmoud Samir Fayed
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Anil Bapat
 
The Ring programming language version 1.5.2 book - Part 71 of 181
The Ring programming language version 1.5.2 book - Part 71 of 181The Ring programming language version 1.5.2 book - Part 71 of 181
The Ring programming language version 1.5.2 book - Part 71 of 181Mahmoud Samir Fayed
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascriptrelay12
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And PatternsAnil Bapat
 
Class 4: Making Procedures
Class 4: Making ProceduresClass 4: Making Procedures
Class 4: Making ProceduresDavid Evans
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programmingSrinivas Narasegouda
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2Philip Schwarz
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8dplunkett
 

La actualidad más candente (20)

7 Methods and Functional Programming
7  Methods and Functional Programming7  Methods and Functional Programming
7 Methods and Functional Programming
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++
 
The Ring programming language version 1.5.2 book - Part 71 of 181
The Ring programming language version 1.5.2 book - Part 71 of 181The Ring programming language version 1.5.2 book - Part 71 of 181
The Ring programming language version 1.5.2 book - Part 71 of 181
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And Patterns
 
Class 4: Making Procedures
Class 4: Making ProceduresClass 4: Making Procedures
Class 4: Making Procedures
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
 
Refactoring
RefactoringRefactoring
Refactoring
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 

Destacado

Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)wolframkriesing
 
Revisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and RefactoringRevisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and RefactoringNorihiro Yoshida
 
Code Smells and How to avoid it
Code Smells and How to avoid itCode Smells and How to avoid it
Code Smells and How to avoid itSyed Shah
 
Refactoring Fest
Refactoring FestRefactoring Fest
Refactoring FestNaresh Jain
 
Code Smells and Its type (With Example)
Code Smells and Its type (With Example)Code Smells and Its type (With Example)
Code Smells and Its type (With Example)Anshul Vinayak
 
DevOps Introduction
DevOps IntroductionDevOps Introduction
DevOps IntroductionRobert Sell
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101Adam Culp
 
Refactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsRefactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsfungfung Chen
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous Integrationdrluckyspin
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
자바 서버 애플리케이션 아키텍처 안티 패턴
자바 서버 애플리케이션 아키텍처 안티 패턴자바 서버 애플리케이션 아키텍처 안티 패턴
자바 서버 애플리케이션 아키텍처 안티 패턴Sungchul Park
 
변경에 강한 애플리케이션, 유기적 애플리케이션
변경에 강한 애플리케이션, 유기적 애플리케이션변경에 강한 애플리케이션, 유기적 애플리케이션
변경에 강한 애플리케이션, 유기적 애플리케이션Sungchul Park
 
02. it정보화전략-보안 아키텍처 도입
02. it정보화전략-보안 아키텍처 도입02. it정보화전략-보안 아키텍처 도입
02. it정보화전략-보안 아키텍처 도입InGuen Hwang
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streamsmattpodwysocki
 
IT전략계획-04.보안 아키텍처
IT전략계획-04.보안 아키텍처IT전략계획-04.보안 아키텍처
IT전략계획-04.보안 아키텍처InGuen Hwang
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift선협 이
 
애자일은 반드시 없어져야 한다
애자일은 반드시 없어져야 한다애자일은 반드시 없어져야 한다
애자일은 반드시 없어져야 한다종범 고
 

Destacado (20)

Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)Day2 - Refactoring (Lecture SS 2015)
Day2 - Refactoring (Lecture SS 2015)
 
Revisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and RefactoringRevisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and Refactoring
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
Code Smells and How to avoid it
Code Smells and How to avoid itCode Smells and How to avoid it
Code Smells and How to avoid it
 
Refactoring Fest
Refactoring FestRefactoring Fest
Refactoring Fest
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Code Smells and Its type (With Example)
Code Smells and Its type (With Example)Code Smells and Its type (With Example)
Code Smells and Its type (With Example)
 
DevOps Introduction
DevOps IntroductionDevOps Introduction
DevOps Introduction
 
Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Refactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsRefactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objects
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous Integration
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
자바 서버 애플리케이션 아키텍처 안티 패턴
자바 서버 애플리케이션 아키텍처 안티 패턴자바 서버 애플리케이션 아키텍처 안티 패턴
자바 서버 애플리케이션 아키텍처 안티 패턴
 
변경에 강한 애플리케이션, 유기적 애플리케이션
변경에 강한 애플리케이션, 유기적 애플리케이션변경에 강한 애플리케이션, 유기적 애플리케이션
변경에 강한 애플리케이션, 유기적 애플리케이션
 
02. it정보화전략-보안 아키텍처 도입
02. it정보화전략-보안 아키텍처 도입02. it정보화전략-보안 아키텍처 도입
02. it정보화전략-보안 아키텍처 도입
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
IT전략계획-04.보안 아키텍처
IT전략계획-04.보안 아키텍처IT전략계획-04.보안 아키텍처
IT전략계획-04.보안 아키텍처
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift
 
애자일은 반드시 없어져야 한다
애자일은 반드시 없어져야 한다애자일은 반드시 없어져야 한다
애자일은 반드시 없어져야 한다
 

Similar a Bad Smell In Codes 1

Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmellhyunglak kim
 
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
 
Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.Andrés Callejas González
 
The programming philosophy of jrql
The programming philosophy of jrqlThe programming philosophy of jrql
The programming philosophy of jrqlmsg systems ag
 
Code Refactoring - 3.0
Code Refactoring - 3.0Code Refactoring - 3.0
Code Refactoring - 3.0Arul Prakash
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaHamad Odhabi
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Refactoring 9~10
Refactoring   9~10Refactoring   9~10
Refactoring 9~10Chris Chen
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
14method in c#
14method in c#14method in c#
14method in c#Sireesh K
 
Legacy Coderetreat @Budapest 2013 02 16
Legacy Coderetreat @Budapest 2013 02 16Legacy Coderetreat @Budapest 2013 02 16
Legacy Coderetreat @Budapest 2013 02 16Adi Bolboaca
 

Similar a Bad Smell In Codes 1 (20)

Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmell
 
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: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.Refactoring: Improving the design of existing code. Chapter 6.
Refactoring: Improving the design of existing code. Chapter 6.
 
Composing method
Composing methodComposing method
Composing method
 
Init() Day 4
Init() Day 4Init() Day 4
Init() Day 4
 
Java
JavaJava
Java
 
The programming philosophy of jrql
The programming philosophy of jrqlThe programming philosophy of jrql
The programming philosophy of jrql
 
Code Refactoring - 3.0
Code Refactoring - 3.0Code Refactoring - 3.0
Code Refactoring - 3.0
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Refactoring 9~10
Refactoring   9~10Refactoring   9~10
Refactoring 9~10
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
 
14method in c#
14method in c#14method in c#
14method in c#
 
Legacy Coderetreat @Budapest 2013 02 16
Legacy Coderetreat @Budapest 2013 02 16Legacy Coderetreat @Budapest 2013 02 16
Legacy Coderetreat @Budapest 2013 02 16
 
30csharp
30csharp30csharp
30csharp
 

Último

Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdfMuhammad Subhan
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireExakis Nelite
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPTiSEO AI
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligenceRevolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligencePrecisely
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...marcuskenyatta275
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxMasterG
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 

Último (20)

Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial IntelligenceRevolutionizing SAP® Processes with Automation and Artificial Intelligence
Revolutionizing SAP® Processes with Automation and Artificial Intelligence
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 

Bad Smell In Codes 1

  • 1. Bad smell in codes – Part 1 If it stinks change it. Presented By: Fuad Bin Omar Rashed Kibria fuad@code71.com rashed@code71.com www.code71.com www.code71.com
  • 2. Smells to be covered •Duplicated code •Long method •Long parameter list •Divergent change •Shotgun surgery
  • 3. Duplicated Code Smell • Same code structure in more than one place. Refactor Extract method and invoke it from both the places.
  • 4. Extract Method • You have a code fragment that can be grouped together. • Turn the fragment into a method whose name explains the purpose of the method.
  • 5. Extract Method (Contd.) void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); }
  • 6. Extract Method (Contd.) void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }
  • 7. Duplicated Code Smell • same expression in two sibling subclasses Refactor • Extract method in both classes. • Pull up field.
  • 8. Pull Up Field • Two subclasses have the same field. • Move the field to the superclass.
  • 9. Pull Up Field (Contd.)
  • 10. Duplicated Code Smell • Code is similar but not the same Refactor: • Use Extract Method to separate the similar bits from the different bits. • Use Form Template Method.
  • 11. Form template method • You have two methods in subclasses that perform similar steps in the same order, yet the steps are different. • Get the steps into methods with the same signature, so that the original methods become the same. Then you can pull them up.
  • 13. Duplicated Code Smell • Methods do the same thing with a different algorithm Refactor: • Choose the clearer of the two algorithms Use • Use Substitute Algorithm.
  • 14. Substitute Algorithm • You want to replace an algorithm with one that is clearer. • Replace the body of the method with the new algorithm.
  • 15. Substitute Algorithm(Contd.) String foundPerson(String[] people) { for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ return "Don"; } if (people[i].equals ("John")){ return "John"; } if (people[i].equals ("Kent")){ return "Kent"; } } return ""; }
  • 16. Substitute Algorithm (Contd.) String foundPerson(String[] people) { List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (int i=0; i<people.length; i++) if (candidates.contains(people[i])) return people[i]; return ""; }
  • 17. Duplicated Code Smell • Duplicated code in two unrelated class. Refactor: • Use Extract Class in one class. • Use the new component to the other. • Decide where the method makes sense.
  • 18. Extract Class • You have one class doing work that should be done by two. • Create a new class and move the relevant fields and methods from the old class into the new class.
  • 20. Long method • Object program having short methods live best and longest. • Little methods are the most valuable. • Longer methods are difficult to understand.
  • 21. Long method • Give methods a good name. • Whenever you feel the need to comment something make it a method. – Group of lines – Even if it is a single line – Even if method call is longer than code itself. – Method length is not the key here. – What the method does and how it does it is important.
  • 23. Long method Smell Use of temporary variable. Refactor Replace temp with query.
  • 24. Replace temp with query • You are using a temporary variable to hold the result of an expression. • Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods
  • 25. Replace temp with query double basePrice = _quantity * _itemPrice; if (basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98;
  • 26. Replace temp with query if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98; ... ... double basePrice() { return _quantity * _itemPrice; }
  • 27. Long method Smell Methods with long list of parameters. Refactor Introduce Parameter Object Preserve Whole Object Method with method Object
  • 28. Introduce Parameter Object • You have a group of parameters that naturally go together. • Replace them with an object.
  • 30. Preserve whole object • You are getting several values from an object and passing these values as parameters in a method call. • Send the whole object instead.
  • 31. Preserve whole object int low = daysTempRange().getLow(); int high = daysTempRange().getHigh(); withinPlan = plan.withinRange(low, high);
  • 32. Preserve whole object withinPlan = plan.withinRange(daysTempRange());
  • 33. Replace method with method object • You have a long method that uses local variables in such a way that you cannot apply Extract Method • Turn the method into its own object so that all the local variables become fields on that object. You can then decompose the method into other methods on the same object.
  • 34. Replace method with method object class Order { double price() { double primaryBasePrice; double secondaryBasePrice; double tertiaryBasePrice; // long computation; } }
  • 35. Replace method with method object
  • 36. Long method Smell • Too many conditions and loops Refactor • With loops, extract the loop and the code within the loop into its own method. • Use Decompose Conditional.
  • 37. Decompose Conditional • You have a complicated conditional (if-then-else) statement. • Extract methods from the condition, then part, and else parts
  • 38. Decompose Conditional if (date.before (SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate;
  • 39. Decompose Conditional if (notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge (quantity);
  • 40. Long Parameter List Smell • A method call requires passing long list of parameters. Refactor • Use Replace Parameter with Method, Preserve whole object or Introduce Parameter Object.
  • 41. Replace Parameter With Method int basePrice = _quantity * _itemPrice; discountLevel = getDiscountLevel(); double finalPrice = discountedPrice (basePrice,discountLevel); int basePrice = _quantity * _itemPrice; double finalPrice = discountedPrice(basePrice);
  • 42. Divergent Change Smell • One class is commonly changed in different ways for different reasons. Refactor • Use Extract class by identifying everything that changes for a particular cause and put them all together.
  • 43. Shotgun Surgery Smell • A small changes in the code force changes in different classes. Refactor • Use Move Method and Move Field to put all the changes into a single class. • If no current class looks like a good candidate, create one. • use Inline Class to bring a whole bunch of behavior together.
  • 44. Move Method • A method is, or will be, using or used by more features of another class than the class on which it is defined. • Create a new method with a similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it altogether.
  • 46. Move Field • A field is, or will be, used by another class more than the class on which it is defined. • Create a new field in the target class, and change all its users.
  • 49. References 1. Refactoring: Improving the Design of Existing Code By Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts 2. www.refactoring.com