SlideShare una empresa de Scribd logo
1 de 45
Code Smells and Refactoring
Ashif Mohammad Iqbal
Sr. Software Engineer
Cefalo Bangladesh Ltd
Satyajit Dey
Sr. Software Engineer
Cefalo Bangladesh Ltd
Technical Debt
Metaphor coined by Ward Cunningham in a 1992 report.
A concept in software development that reflects the implied
cost of additional rework caused by choosing an easy
solution now instead of using a better approach that would
take longer.
Stakeholders Goals
● Determine product/market fit
● Critical need to ship products early
● Meet customer needs
● Seize emerging opportunities
Causes of Technical Debt
● Business pressure
● Lack of understanding of the consequences of technical debt
● Failing to combat the strict coherence of components
● Lack of tests
● Lack of documentation
● Lack of interaction between team members
● Long-term simultaneous development in several branches
● Delayed refactoring
● Lack of compliance monitoring
● Incompetence
Types of Technical Debt
1. Code debt
2. Design & Architecture debt
3. Test debt
4. Documentation debt
Technical Debt
Figure - Technical debt: The vicious cycle
Code Smells
A code smell is a surface indication that usually
corresponds to a deeper problem in the system.
—Martin Fowler
Common Code Smells
● Comments
● Uncommunicative Name
● Long method
● Long parameter list
● Data Clumps
● Large class
● Duplicate Code
● Primitive Obsession
● Divergent Code
● Shotgun Surgery
● Switch Statements
● Lazy Class
And many more…..
Comments
● Should only be used to clarify "why" not "what".
● Can quickly become verbose and reduce code clarity.
Please don’t do that.
Uncommunicative Name
● Choose names that communicate intent
● Pick the best name for the time, change it later if necessary
Long Method
Signs and Symptoms
A method contains too many lines of code.
Reason
Developers start coding without reading the existing implementation.
Treatment
● Extract Method
● Replace Method with Method Object
● Replace temp with query
Long Method
Extract Method
Before
After
Long Method
Replace method with method object
Before
After
Long Method
Replace temp
with query
Before
After
Long Parameter List
Signs and Symptoms
More than three or four parameters for a method.
Reason
● Trying to do too many things in a method.
● Trying to minimize dependencies between objects.
Treatment
● Replace parameters with method call.
● Preserve whole object.
● Introduce parameter object.
Long Parameter List
Replace parameters with method call
Before
After
Long Parameter List
Preserve whole object
Before
After
Long Parameter List
Introduce parameter object
Before
After
Long Parameter List
Benefits
● Improving readability of code.
● Possibly reduces code duplication that was not noticed earlier.
Exceptions
Sometimes we might decide to go with a long parameters list.
● Passing a whole object would cause unwanted dependency between objects.
● In some cases the parameters can be unrelated. Grouping them in a parameter
object won’t make any sense.
Data Clumps
Signs and Symptoms
Sometimes different parts of the code contain identical groups of variables
Reasons for the Problem
● Copypasta programming
Treatment
● Extract Class
● Introduce Parameter Object
● Preserve whole object
Data Clumps
Before
After
Large Class
Signs and Symptoms
A class contains many fields/methods/lines of code.
Reason
Developers find it mentally less taxing to place a new feature in an existing class than
to create a new class for small feature.
Treatment
● Extract Class
● Extract Subclass
● Extract Interface
Duplicate Code
Signs and Symptoms
● Code fragments look almost identical.
● Same expression in two or more method in same class
Reasons for the Problem
● Multiple programmers doing same thing at the same time
● Novice programmers may not resist themselves to do Copy/Pasta
● Scary authors don’t allow to refactor their code
Treatment
● Extract Method
● Pull Up Field
● Form Template Method, Substitute Algorithm
Duplicate Code
Before
Duplicate Code
After
Primitive Obsession
Signs and Symptoms
● Use of primitives instead of small objects for simple tasks
● Using arrays, map or dictionaries to represent specific object
Reasons for the Problem
● “Just a field for storing some data!” the programmer said
● Creating a primitive field is easier
Treatment
● Replace Data values with Object
● Replace array/map with object
Primitive Obsession
After
Replace data value with object
Before
Primitive Obsession
After
Replace array with object
Before
Divergent Change
Signs and Symptoms
You find yourself having to change many unrelated methods when you make changes
to a class
Reasons for the Problem
● Often these divergent modifications are due to poor program structure or
"copypasta programming”.
Treatment
● Split up the behavior of the class via Extract Class.
Divergent Change
Divergent Change
Shotgun Surgery
Signs and Symptoms
A single change impact many other classes.
Reasons for the Problem
● Poor separation of concerns.
● Failure to understand responsibilities(SRP)
Treatment
● Move Method
● Move Field
● Inline Class.
Shotgun Surgery
Shotgun Surgery
Switch Statements
Signs and Symptoms
You have a complex switch operator or sequence of if statements.
Reasons for the Problem
● Switch Statements can be scattered in several places
● Need to find all SS for adding new case.
Treatment
● To isolate switch and put it in the right class, you may need Extract Method and then Move
Method.
● Think about Polymorphism
Switch Statements
Switch Statements
Replace type code with subclasses
Switch Statements
Replace type code with state or strategy
Switch Statements
Replace conditional with polymorphism
Switch Statements
Benefits
● If you need to add a new type code, you can just add a new subclass without
touching the existing code. This follows the Open/Closed Principle.
● Instead of asking an object for its state and performing actions based on that it is
easier to let the object decide what to do. This means following the Tell, Don't
Ask Principle.
● Removes duplicate code when you have several similar conditions.
Exceptions
In some cases replacing switch statements is not necessary:
● If the switch operator performs very simple actions, there is no reason to change
it.
● A factory method or an abstract factory might use switch statements to create
classes.
Lazy Class
Signs and Symptoms
If a class doesn’t do enough to earn your attention, it should be deleted.
Reasons for the Problem
● After refactoring the Class has become less important
● May be designed for future needs!
Treatment
● Inline Class
● Collapse Hierarchy.
“Any fool can write code that a computer can understand. Good
programmers write code that humans can understand.”
― Martin Fowler
https://github.com/Cefalo/lets-learn-refactoring
References
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal

Más contenido relacionado

La actualidad más candente

Input Space Partitioning
Input Space PartitioningInput Space Partitioning
Input Space Partitioning
Riyad Parvez
 
Better tests automagically (big sky dev con 2015)
Better tests automagically (big sky dev con 2015)Better tests automagically (big sky dev con 2015)
Better tests automagically (big sky dev con 2015)
roblund
 

La actualidad más candente (20)

Equivalence partitions analysis
Equivalence partitions analysisEquivalence partitions analysis
Equivalence partitions analysis
 
Coding standards
Coding standardsCoding standards
Coding standards
 
Testing techniques
Testing techniquesTesting techniques
Testing techniques
 
Coding standards and guidelines
Coding standards and guidelinesCoding standards and guidelines
Coding standards and guidelines
 
Input Space Partitioning
Input Space PartitioningInput Space Partitioning
Input Space Partitioning
 
Equivalence class testing
Equivalence  class testingEquivalence  class testing
Equivalence class testing
 
Boundary value analysis and equivalence partitioning
Boundary value analysis and equivalence partitioningBoundary value analysis and equivalence partitioning
Boundary value analysis and equivalence partitioning
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
 
Software Testing Techniques
Software Testing TechniquesSoftware Testing Techniques
Software Testing Techniques
 
Code Review
Code ReviewCode Review
Code Review
 
5 black box and grey box testing
5   black box and grey box testing5   black box and grey box testing
5 black box and grey box testing
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
 
Code Review
Code ReviewCode Review
Code Review
 
Better tests automagically (big sky dev con 2015)
Better tests automagically (big sky dev con 2015)Better tests automagically (big sky dev con 2015)
Better tests automagically (big sky dev con 2015)
 
Code review
Code reviewCode review
Code review
 
Black box testing
Black box testingBlack box testing
Black box testing
 
Debbuging
DebbugingDebbuging
Debbuging
 
Behavioral design patterns presentation
Behavioral design patterns presentationBehavioral design patterns presentation
Behavioral design patterns presentation
 

Similar a Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal

c-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.pptc-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.ppt
VinayakHospet1
 

Similar a Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal (20)

Improving your code design using Java
Improving your code design using JavaImproving your code design using Java
Improving your code design using Java
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Clean Code
Clean CodeClean Code
Clean Code
 
Refactoring
RefactoringRefactoring
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
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
PHP Dublin Meetup - Clean Code in PHP
PHP Dublin Meetup - Clean Code in PHPPHP Dublin Meetup - Clean Code in PHP
PHP Dublin Meetup - Clean Code in PHP
 
Refactoring
RefactoringRefactoring
Refactoring
 
Code Smells - Refactoring
Code Smells - RefactoringCode Smells - Refactoring
Code Smells - Refactoring
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approach
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developer
 
c-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.pptc-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.ppt
 
Javascript Programming according to Industry Standards.pptx
Javascript Programming according to Industry Standards.pptxJavascript Programming according to Industry Standards.pptx
Javascript Programming according to Industry Standards.pptx
 
[DSC Europe 22] Engineers guide for shepherding models in to production - Mar...
[DSC Europe 22] Engineers guide for shepherding models in to production - Mar...[DSC Europe 22] Engineers guide for shepherding models in to production - Mar...
[DSC Europe 22] Engineers guide for shepherding models in to production - Mar...
 
Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)
 
Clean code
Clean codeClean code
Clean code
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing code
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 

Más de Cefalo

Más de Cefalo (12)

Overview of Cookies in HTTP - Miran al Mehrab
Overview of Cookies in HTTP - Miran al MehrabOverview of Cookies in HTTP - Miran al Mehrab
Overview of Cookies in HTTP - Miran al Mehrab
 
Handshaking with HTTPS - Rafiul Islam
Handshaking with HTTPS - Rafiul IslamHandshaking with HTTPS - Rafiul Islam
Handshaking with HTTPS - Rafiul Islam
 
Evolution of HTTP - Miran Al Mehrab
Evolution of HTTP - Miran Al MehrabEvolution of HTTP - Miran Al Mehrab
Evolution of HTTP - Miran Al Mehrab
 
Content Negotiation in HTTP - Ibnul Tahsin Bhuiyan
Content Negotiation in HTTP - Ibnul Tahsin BhuiyanContent Negotiation in HTTP - Ibnul Tahsin Bhuiyan
Content Negotiation in HTTP - Ibnul Tahsin Bhuiyan
 
Conditional Requests in HTTP - Nafis Fuad
Conditional Requests in HTTP - Nafis FuadConditional Requests in HTTP - Nafis Fuad
Conditional Requests in HTTP - Nafis Fuad
 
Tips to kick-start your Software Engineering Career - Ferdous Mahmud Shaon
Tips to kick-start your Software Engineering Career - Ferdous Mahmud ShaonTips to kick-start your Software Engineering Career - Ferdous Mahmud Shaon
Tips to kick-start your Software Engineering Career - Ferdous Mahmud Shaon
 
Rest API Authentication - Uttom Akash
Rest API Authentication - Uttom AkashRest API Authentication - Uttom Akash
Rest API Authentication - Uttom Akash
 
Overview of REST - Raihan Ullah
Overview of REST - Raihan UllahOverview of REST - Raihan Ullah
Overview of REST - Raihan Ullah
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud Shaon
 
Brief of Caching - Rafiul Islam
Brief of Caching - Rafiul IslamBrief of Caching - Rafiul Islam
Brief of Caching - Rafiul Islam
 
Basics of HTTP - Nafis Fuad
Basics of HTTP - Nafis FuadBasics of HTTP - Nafis Fuad
Basics of HTTP - Nafis Fuad
 
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul HakimCross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul Hakim
 

Último

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Último (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 

Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal

  • 1. Code Smells and Refactoring Ashif Mohammad Iqbal Sr. Software Engineer Cefalo Bangladesh Ltd Satyajit Dey Sr. Software Engineer Cefalo Bangladesh Ltd
  • 2. Technical Debt Metaphor coined by Ward Cunningham in a 1992 report. A concept in software development that reflects the implied cost of additional rework caused by choosing an easy solution now instead of using a better approach that would take longer.
  • 3. Stakeholders Goals ● Determine product/market fit ● Critical need to ship products early ● Meet customer needs ● Seize emerging opportunities
  • 4. Causes of Technical Debt ● Business pressure ● Lack of understanding of the consequences of technical debt ● Failing to combat the strict coherence of components ● Lack of tests ● Lack of documentation ● Lack of interaction between team members ● Long-term simultaneous development in several branches ● Delayed refactoring ● Lack of compliance monitoring ● Incompetence
  • 5. Types of Technical Debt 1. Code debt 2. Design & Architecture debt 3. Test debt 4. Documentation debt
  • 6. Technical Debt Figure - Technical debt: The vicious cycle
  • 7. Code Smells A code smell is a surface indication that usually corresponds to a deeper problem in the system. —Martin Fowler
  • 8. Common Code Smells ● Comments ● Uncommunicative Name ● Long method ● Long parameter list ● Data Clumps ● Large class ● Duplicate Code ● Primitive Obsession ● Divergent Code ● Shotgun Surgery ● Switch Statements ● Lazy Class And many more…..
  • 9. Comments ● Should only be used to clarify "why" not "what". ● Can quickly become verbose and reduce code clarity. Please don’t do that.
  • 10. Uncommunicative Name ● Choose names that communicate intent ● Pick the best name for the time, change it later if necessary
  • 11. Long Method Signs and Symptoms A method contains too many lines of code. Reason Developers start coding without reading the existing implementation. Treatment ● Extract Method ● Replace Method with Method Object ● Replace temp with query
  • 13. Long Method Replace method with method object Before After
  • 14. Long Method Replace temp with query Before After
  • 15. Long Parameter List Signs and Symptoms More than three or four parameters for a method. Reason ● Trying to do too many things in a method. ● Trying to minimize dependencies between objects. Treatment ● Replace parameters with method call. ● Preserve whole object. ● Introduce parameter object.
  • 16. Long Parameter List Replace parameters with method call Before After
  • 17. Long Parameter List Preserve whole object Before After
  • 18. Long Parameter List Introduce parameter object Before After
  • 19. Long Parameter List Benefits ● Improving readability of code. ● Possibly reduces code duplication that was not noticed earlier. Exceptions Sometimes we might decide to go with a long parameters list. ● Passing a whole object would cause unwanted dependency between objects. ● In some cases the parameters can be unrelated. Grouping them in a parameter object won’t make any sense.
  • 20. Data Clumps Signs and Symptoms Sometimes different parts of the code contain identical groups of variables Reasons for the Problem ● Copypasta programming Treatment ● Extract Class ● Introduce Parameter Object ● Preserve whole object
  • 22. Large Class Signs and Symptoms A class contains many fields/methods/lines of code. Reason Developers find it mentally less taxing to place a new feature in an existing class than to create a new class for small feature. Treatment ● Extract Class ● Extract Subclass ● Extract Interface
  • 23. Duplicate Code Signs and Symptoms ● Code fragments look almost identical. ● Same expression in two or more method in same class Reasons for the Problem ● Multiple programmers doing same thing at the same time ● Novice programmers may not resist themselves to do Copy/Pasta ● Scary authors don’t allow to refactor their code Treatment ● Extract Method ● Pull Up Field ● Form Template Method, Substitute Algorithm
  • 26. Primitive Obsession Signs and Symptoms ● Use of primitives instead of small objects for simple tasks ● Using arrays, map or dictionaries to represent specific object Reasons for the Problem ● “Just a field for storing some data!” the programmer said ● Creating a primitive field is easier Treatment ● Replace Data values with Object ● Replace array/map with object
  • 27. Primitive Obsession After Replace data value with object Before
  • 29. Divergent Change Signs and Symptoms You find yourself having to change many unrelated methods when you make changes to a class Reasons for the Problem ● Often these divergent modifications are due to poor program structure or "copypasta programming”. Treatment ● Split up the behavior of the class via Extract Class.
  • 32. Shotgun Surgery Signs and Symptoms A single change impact many other classes. Reasons for the Problem ● Poor separation of concerns. ● Failure to understand responsibilities(SRP) Treatment ● Move Method ● Move Field ● Inline Class.
  • 35. Switch Statements Signs and Symptoms You have a complex switch operator or sequence of if statements. Reasons for the Problem ● Switch Statements can be scattered in several places ● Need to find all SS for adding new case. Treatment ● To isolate switch and put it in the right class, you may need Extract Method and then Move Method. ● Think about Polymorphism
  • 37. Switch Statements Replace type code with subclasses
  • 38. Switch Statements Replace type code with state or strategy
  • 40. Switch Statements Benefits ● If you need to add a new type code, you can just add a new subclass without touching the existing code. This follows the Open/Closed Principle. ● Instead of asking an object for its state and performing actions based on that it is easier to let the object decide what to do. This means following the Tell, Don't Ask Principle. ● Removes duplicate code when you have several similar conditions. Exceptions In some cases replacing switch statements is not necessary: ● If the switch operator performs very simple actions, there is no reason to change it. ● A factory method or an abstract factory might use switch statements to create classes.
  • 41. Lazy Class Signs and Symptoms If a class doesn’t do enough to earn your attention, it should be deleted. Reasons for the Problem ● After refactoring the Class has become less important ● May be designed for future needs! Treatment ● Inline Class ● Collapse Hierarchy.
  • 42. “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” ― Martin Fowler

Notas del editor

  1. Sometimes stakeholders set unrealistic deadline of a project.
  2. We treat everything in the trash as another trash, no matters it is valuable or less valuable
  3. Generally, any method longer than ten lines should make you start asking questions. The majority of a programmer’s time is spent reading code rather than writing code It is usually a sign that the method has too many responsibilities Long methods make code hard to maintain and debug If there are local variables or parameters that prevent extracting a method, replace temp with query, introduce a parameter object, or preserve whole object. If there are conditional operators, you can try to decompose the conditional.
  4. Extract method
  5. In this example keep in mind that the local variable is preventing us from using extract method. The goal here is to present how to make it possible.
  6. In this example keep in mind that the local variable is preventing us from using extract method. The goal here is to present how to make it possible.
  7. It is not really clear what each parameter does. To find out you are forced to read the documentation. If the parameters come from different objects, introduce a parameter object. If the parameter can be obtained from another object, replace parameter with a method call. The object can be a field in the class or passed as a parameter. If the parameters belong to a single object, preserve whole object.
  8. In this example keep in mind that the local variable is preventing us from using extract method. The goal here is to present how to make it possible.
  9. In this example keep in mind that the local variable is preventing us from using extract method. The goal here is to present how to make it possible.
  10. For example: (such as parameters for connecting to a database) If repeating data comprises the fields of a class, use Extract Class to move the fields to their own class. If the same data clumps are passed in the parameters of methods, use Introduce Parameter Object to set them off as a class. If some of the data is passed to other methods, think about passing the entire data object to the method instead of just individual fields. Preserve Whole Object will help with this.
  11. Classes usually start small. But over time, they get bloated as the program grows.
  12. Primitive obsessions are born in moments of weakness Then another field was needed and added in the same way.
  13. For example, when adding a new product type you have to change the methods for finding, displaying, and ordering products. Payoff Improves code organization. Reduces code duplication. Simplifies support.
  14. Shotgun Surgery resembles Divergent Change but is actually the opposite smell. Divergent Change is when many changes are made to a single class. Shotgun Surgery refers to when a single change is made to multiple classes simultaneously
  15. spreading around logic that should probably be in one place if you add a value to one switch statement you’re likely to need to hunt down all the other ones and change them too. Cyclometic complexity = Number of decisions in the source code