SlideShare una empresa de Scribd logo
1 de 33
Descargar para leer sin conexión
Identify and Correct
Common Code Smells
11/12/2014
http://submain.com/webcasts/identify-and-correct-common-code-smells/
for the webcast recording and slides download
Webcast Housekeeping
Audio
 Connect viaVoIP (default)
 Plug in a headset or turn up your speakers
 Select “User Mic and Speakers” in Camera andVoice
 Connect via Phone
 Select “Dial In” in Audio Options
 Call 1 (206) 453-2087 (see confirmation email for local numbers)
 PIN: 685568#
Asking A Question
 Use the Chat window in the bottom left corner
 Questions will be addressed at the end of the webcast
Recording
 A recording download link will be sent to all registrants within a few days
11/12/2014 Copyright © SubMain 2014 Slide 2
Introduction
Presenter
Steve Smith
Microsoft MVP, RD
CTO, Falafel Software
(g)host
Serge Baranovsky
Chief Strategy Officer,
SubMain
11/12/2014 Copyright © SubMain 2014 3
Steve Smith
Pluralsight Author
 SOLID Principles, Design Patterns
 DDD, N-Tier Architecture
 Kanban, Web PerformanceTuning/Testing
 Refactoring and Code Smells
Blog
 Ardalis.com
More
 http://about.me/stevenasmith
11/12/2014 Copyright © SubMain 2014 4
@ardalis
StevenAndrewSmith
stevenandrewsmith
What are ‘Code Smells’ ?
11/12/2014 Copyright © SubMain 2014 5
Bad Smells in Code
Described by Kent Beck and Martin Fowler in
Refactoring Fundamentals
Intentionally vague term
Context-dependent; use your judgment
11/12/2014 Copyright © SubMain 2014 Slide 6
Principle of Least Surprise
Design your API to behave as programmers would
expect
11/12/2014 Copyright © SubMain 2014 Slide 7
Kent Beck’s Rules of Simple Design
Well-designed code should:
 Run all the tests (successfully)
 Contain no duplicate code
 Express all the ideas its authors wish to express
 Minimize classes and methods
11/12/2014 Copyright © SubMain 2014 Slide 8
Code Smell: Long Method
Prefer short methods to long methods
 Smaller methods can have more descriptive names
 Smaller methods are easier to understand at a glance
 Less likely to duplicate code between small methods
Strive for no more than 10 lines of code per method
Do not tolerate methods that do not fit on one screen
11/12/2014 Copyright © SubMain 2014 Slide 9
Example: Long Method
11/12/2014 Copyright © SubMain 2014 Slide 10
Code Smell: Large Class
Similar to Long Method
Usually violates Single Responsibility Principle
May have
 Too many instance variables
 Too many methods
 All of the above
Typically lacks cohesion
 Several classes baked into one
11/12/2014 Copyright © SubMain 2014 Slide 11
Code Smell: Primitive Obsession
Abusing primitives instead of using better
abstractions
Less intention-revealing
Leads to scattered business logic
 Guard clauses
 Validation
11/12/2014 Copyright © SubMain 2014 Slide 12
Example: Primitive Obsession
// method call relying on primitives only
AddHoliday(7,4);
11/12/2014 Copyright © SubMain 2014 Slide 13
Example: Primitive Obsession
// method call relying on primitives only
AddHoliday(7,4);
// use a higher level type
Date independenceDay = new Date(7,4);
AddHoliday(independenceDay);
11/12/2014 Copyright © SubMain 2014 Slide 14
Example: Primitive Obsession
// go even further
public class July {
private const int _month = 7;
public static readonly Date Fourth {
get { return new Date(_month, 4); } } }
AddHoliday(July.Fourth);
11/12/2014 Copyright © SubMain 2014 Slide 15
Example: Primitive Obsession
// method call relying on primitives
DrawLine(5,20,25,40);
3/25/2014 Copyright © SubMain 2014 Slide 16
Example: Primitive Obsession
// method call relying on primitives
DrawLine(5,20,25,40,0,0,255);
11/12/2014 Copyright © SubMain 2014 Slide 17
Example: Primitive Obsession
// method call relying on primitives
TransferFunds(23423, 23434, 48432);
11/12/2014 Copyright © SubMain 2014 Slide 18
Example: Primitive Obsession
// method call relying on primitives
TransferFunds(23423, 23434, 48432);
// refactored to be more clear and use higher level objects
Account transferFrom = _accountRepository.Get(23423);
Account transferTo = _accountRepository.Get(23434);
var transferAmount = new Money(48432, Currency.USD);
TransferFunds(transferFrom, transferTo, transferAmount);
3/25/2014 Copyright © SubMain 2014 Slide 19
Primitive Obsession Common
Examples
Phone Numbers
Social Security Numbers
ZIP/Postal Codes
Money
Age
Temperature
Address
Credit Card Information
3/25/2014 Copyright © SubMain 2014 Slide 20
Code Smell: Data Clumps
Sets of data items that are always used together, but
are not organized together
Similar to Primitive Obsession, but always deals with
several items
Frequently give rise to long parameter lists (another
smell)
11/12/2014 Copyright © SubMain 2014 Slide 21
Example: Data Clumps
// data clumps on an order
Order.CreditCardName = creditCardName;
Order.CreditCardNumber = creditCardNumber;
Order.ExpiresMonth = creditCardMonth;
Order.ExpiresYear = creditCardYear;
Order.SecurityCode = creditCardSecurityCode;
11/12/2014 Copyright © SubMain 2014 Slide 22
Example: Data Clumps
// data clumps on an order
Order.CreditCardName = creditCardName;
Order.CreditCardNumber = creditCardNumber;
Order.ExpiresMonth = creditCardMonth;
Order.ExpiresYear = creditCardYear;
Order.SecurityCode = creditCardSecurityCode;
// refactored by Extracting a new CreditCardInfo class
CreditCardInfo cardInfo = new CreditCardInfo(
creditCardNme, creditCardNumber, creditCardMonth,
creditCardYear, creditCardSecurityCode);
Order.CreditCard = cardInfo;
11/12/2014 Copyright © SubMain 2014 Slide 23
Code Smell: Poor Names
Names should:
Be descriptive
Be at appropriate abstraction
level
Use standard terms
Be unambiguous
Avoid encodings
Describe side effects
Be longer when scope is large
11/12/2014 Copyright © SubMain 2014 Slide 24
Example: Poor Names
public static List<int> Generate(int n)
{
var x = new List<int>();
for (int i = 2; n > 1; i++)
for (; n % i == 0; n /= i)
x.Add(i);
return x;
}
11/12/2014 Copyright © SubMain 2014 Slide 25
Example: Poor Names
public static List<int> GeneratePrimeFactorsOf(int input)
{
var primeFactors = new List<int>();
for (int candidateFactor = 2; input > 1; candidateFactor++)
while (input % candidateFactor == 0)
{
primeFactors.Add(candidateFactor);
input /= candidateFactor;
}
return primeFactors;
}
// Usage:
var factors = GeneratePrimeFactorsOf(input);
11/12/2014 Copyright © SubMain 2014 Slide 26
Example: Inappropriate Abstraction Level
public class User
{
public string UserName { get; set; }
public static int GetTotalUserCountInDatabaseTable()
{
throw new NotImplementedException();
}
public static SqlDataReader GetDataReaderWithRoles(string userName)
{
throw new NotImplementedException();
}
}
11/12/2014 Copyright © SubMain 2014 Slide 27
Example: Inappropriate Abstraction Level
public class User
{
public string UserName { get; set; }
public IEnumerable<Role> IsInRoles()
{
throw new NotImplementedException();
}
}
11/12/2014 Copyright © SubMain 2014 Slide 28
public class SqlUserRepository
{
public int TotalUserCount()
{
throw new NotImplementedException();
}
public IEnumerable<Role> UserIsInRoles(string userName)
{
throw new NotImplementedException();
}
}
How CodeIt.Right Helps
11/12/2014 Copyright © SubMain 2014 29
What is CodeIt.Right
 Code Quality Analysis and Metrics
 Automated Code Review process
 Automated way to discover and
fix code smells
 Automatic and safe refactoring
of issues into conforming code
 Ensure your code adheres to
(your) predefined design
requirements and best coding
practices
11/12/2014 Copyright © SubMain 2014 30
What is CodeIt.Right - continued
Instant Code Review – real-time code checking
OnDemand Analysis
Source Control Check-In Policy
Build Process Integration
Hundreds of rules
 Security, Performance, Usage,
Design, Maintainability,
Exception Handling, Globalization,
Async, and more
11/12/2014 Copyright © SubMain 2014 31
Demo
Discover and Fix Code Smells
Coding Pattern Examples
 ISerializable/Custom Serialization
 Dispose/Finalize
11/12/2014 Copyright © SubMain 2014 32
Q&A
Questions?
Email - customer-service@submain.com
Video - submain.com/codeit.right/video
Download the free CodeIt.Right trial at submain.com/codeit.right
11/12/2014 Copyright © SubMain 2014 33
1 (800) 936-2134
http://submain.com/webcasts/identify-and-correct-common-code-smells/
for the webcast recording and slides download

Más contenido relacionado

Similar a Webcast: Identify and Correct Common Code Smells

Avr_presentation
Avr_presentationAvr_presentation
Avr_presentationPakky .
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Darwin Biler
 
How to Close the SecOps Gap
How to Close the SecOps GapHow to Close the SecOps Gap
How to Close the SecOps GapBMC Software
 
Secure Drupal, from start to finish
Secure Drupal, from start to finishSecure Drupal, from start to finish
Secure Drupal, from start to finishBoy Baukema
 
Secure Drupal, from start to finish (European Drupal Days 2015)
Secure Drupal, from start to finish (European Drupal Days 2015)Secure Drupal, from start to finish (European Drupal Days 2015)
Secure Drupal, from start to finish (European Drupal Days 2015)Eugenio Minardi
 
PlumChoice: The New Cardinal Rules of IoT Adoption
PlumChoice: The New Cardinal Rules of IoT AdoptionPlumChoice: The New Cardinal Rules of IoT Adoption
PlumChoice: The New Cardinal Rules of IoT Adoptionplumchoice
 
Avoiding Over Design and Under Design
Avoiding Over Design and Under DesignAvoiding Over Design and Under Design
Avoiding Over Design and Under DesignTechWell
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Handling Technology Trauma
Handling Technology TraumaHandling Technology Trauma
Handling Technology TraumaCynthia Clay
 
Implementing Cloud-Based DevOps for Distributed Agile Projects
Implementing Cloud-Based DevOps for Distributed Agile ProjectsImplementing Cloud-Based DevOps for Distributed Agile Projects
Implementing Cloud-Based DevOps for Distributed Agile ProjectsTechWell
 
Getting Started with Apache Geode
Getting Started with Apache GeodeGetting Started with Apache Geode
Getting Started with Apache GeodeJohn Blum
 
Plugin for other browsers - webRTC Conference and Expo June 2014 @ atlanta
Plugin for other browsers - webRTC Conference and Expo June 2014 @ atlantaPlugin for other browsers - webRTC Conference and Expo June 2014 @ atlanta
Plugin for other browsers - webRTC Conference and Expo June 2014 @ atlantaAlexandre Gouaillard
 
Developing Rich Clients with the Eclipse 4 Application Platform
Developing Rich Clients with the Eclipse 4 Application PlatformDeveloping Rich Clients with the Eclipse 4 Application Platform
Developing Rich Clients with the Eclipse 4 Application PlatformKai Tödter
 
A Data-Driven Approach for Mobile Testing and Automation
A Data-Driven Approach for Mobile Testing and AutomationA Data-Driven Approach for Mobile Testing and Automation
A Data-Driven Approach for Mobile Testing and AutomationTechWell
 
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Zend by Rogue Wave Software
 

Similar a Webcast: Identify and Correct Common Code Smells (20)

Avr_presentation
Avr_presentationAvr_presentation
Avr_presentation
 
Avr presentation
Avr   presentationAvr   presentation
Avr presentation
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
How to Close the SecOps Gap
How to Close the SecOps GapHow to Close the SecOps Gap
How to Close the SecOps Gap
 
Secure Drupal, from start to finish
Secure Drupal, from start to finishSecure Drupal, from start to finish
Secure Drupal, from start to finish
 
Secure Drupal, from start to finish (European Drupal Days 2015)
Secure Drupal, from start to finish (European Drupal Days 2015)Secure Drupal, from start to finish (European Drupal Days 2015)
Secure Drupal, from start to finish (European Drupal Days 2015)
 
PlumChoice: The New Cardinal Rules of IoT Adoption
PlumChoice: The New Cardinal Rules of IoT AdoptionPlumChoice: The New Cardinal Rules of IoT Adoption
PlumChoice: The New Cardinal Rules of IoT Adoption
 
Avoiding Over Design and Under Design
Avoiding Over Design and Under DesignAvoiding Over Design and Under Design
Avoiding Over Design and Under Design
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Handling Technology Trauma
Handling Technology TraumaHandling Technology Trauma
Handling Technology Trauma
 
Implementing Cloud-Based DevOps for Distributed Agile Projects
Implementing Cloud-Based DevOps for Distributed Agile ProjectsImplementing Cloud-Based DevOps for Distributed Agile Projects
Implementing Cloud-Based DevOps for Distributed Agile Projects
 
Getting Started with Apache Geode
Getting Started with Apache GeodeGetting Started with Apache Geode
Getting Started with Apache Geode
 
Plugin for other browsers - webRTC Conference and Expo June 2014 @ atlanta
Plugin for other browsers - webRTC Conference and Expo June 2014 @ atlantaPlugin for other browsers - webRTC Conference and Expo June 2014 @ atlanta
Plugin for other browsers - webRTC Conference and Expo June 2014 @ atlanta
 
David Rodriguez - davidjguru CV 2024 updated
David Rodriguez - davidjguru CV 2024 updatedDavid Rodriguez - davidjguru CV 2024 updated
David Rodriguez - davidjguru CV 2024 updated
 
Developing Rich Clients with the Eclipse 4 Application Platform
Developing Rich Clients with the Eclipse 4 Application PlatformDeveloping Rich Clients with the Eclipse 4 Application Platform
Developing Rich Clients with the Eclipse 4 Application Platform
 
A Data-Driven Approach for Mobile Testing and Automation
A Data-Driven Approach for Mobile Testing and AutomationA Data-Driven Approach for Mobile Testing and Automation
A Data-Driven Approach for Mobile Testing and Automation
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
 
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)
 
2014 cf summit_clustering
2014 cf summit_clustering2014 cf summit_clustering
2014 cf summit_clustering
 

Último

SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 

Último (20)

SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 

Webcast: Identify and Correct Common Code Smells

  • 1. Identify and Correct Common Code Smells 11/12/2014 http://submain.com/webcasts/identify-and-correct-common-code-smells/ for the webcast recording and slides download
  • 2. Webcast Housekeeping Audio  Connect viaVoIP (default)  Plug in a headset or turn up your speakers  Select “User Mic and Speakers” in Camera andVoice  Connect via Phone  Select “Dial In” in Audio Options  Call 1 (206) 453-2087 (see confirmation email for local numbers)  PIN: 685568# Asking A Question  Use the Chat window in the bottom left corner  Questions will be addressed at the end of the webcast Recording  A recording download link will be sent to all registrants within a few days 11/12/2014 Copyright © SubMain 2014 Slide 2
  • 3. Introduction Presenter Steve Smith Microsoft MVP, RD CTO, Falafel Software (g)host Serge Baranovsky Chief Strategy Officer, SubMain 11/12/2014 Copyright © SubMain 2014 3
  • 4. Steve Smith Pluralsight Author  SOLID Principles, Design Patterns  DDD, N-Tier Architecture  Kanban, Web PerformanceTuning/Testing  Refactoring and Code Smells Blog  Ardalis.com More  http://about.me/stevenasmith 11/12/2014 Copyright © SubMain 2014 4 @ardalis StevenAndrewSmith stevenandrewsmith
  • 5. What are ‘Code Smells’ ? 11/12/2014 Copyright © SubMain 2014 5
  • 6. Bad Smells in Code Described by Kent Beck and Martin Fowler in Refactoring Fundamentals Intentionally vague term Context-dependent; use your judgment 11/12/2014 Copyright © SubMain 2014 Slide 6
  • 7. Principle of Least Surprise Design your API to behave as programmers would expect 11/12/2014 Copyright © SubMain 2014 Slide 7
  • 8. Kent Beck’s Rules of Simple Design Well-designed code should:  Run all the tests (successfully)  Contain no duplicate code  Express all the ideas its authors wish to express  Minimize classes and methods 11/12/2014 Copyright © SubMain 2014 Slide 8
  • 9. Code Smell: Long Method Prefer short methods to long methods  Smaller methods can have more descriptive names  Smaller methods are easier to understand at a glance  Less likely to duplicate code between small methods Strive for no more than 10 lines of code per method Do not tolerate methods that do not fit on one screen 11/12/2014 Copyright © SubMain 2014 Slide 9
  • 10. Example: Long Method 11/12/2014 Copyright © SubMain 2014 Slide 10
  • 11. Code Smell: Large Class Similar to Long Method Usually violates Single Responsibility Principle May have  Too many instance variables  Too many methods  All of the above Typically lacks cohesion  Several classes baked into one 11/12/2014 Copyright © SubMain 2014 Slide 11
  • 12. Code Smell: Primitive Obsession Abusing primitives instead of using better abstractions Less intention-revealing Leads to scattered business logic  Guard clauses  Validation 11/12/2014 Copyright © SubMain 2014 Slide 12
  • 13. Example: Primitive Obsession // method call relying on primitives only AddHoliday(7,4); 11/12/2014 Copyright © SubMain 2014 Slide 13
  • 14. Example: Primitive Obsession // method call relying on primitives only AddHoliday(7,4); // use a higher level type Date independenceDay = new Date(7,4); AddHoliday(independenceDay); 11/12/2014 Copyright © SubMain 2014 Slide 14
  • 15. Example: Primitive Obsession // go even further public class July { private const int _month = 7; public static readonly Date Fourth { get { return new Date(_month, 4); } } } AddHoliday(July.Fourth); 11/12/2014 Copyright © SubMain 2014 Slide 15
  • 16. Example: Primitive Obsession // method call relying on primitives DrawLine(5,20,25,40); 3/25/2014 Copyright © SubMain 2014 Slide 16
  • 17. Example: Primitive Obsession // method call relying on primitives DrawLine(5,20,25,40,0,0,255); 11/12/2014 Copyright © SubMain 2014 Slide 17
  • 18. Example: Primitive Obsession // method call relying on primitives TransferFunds(23423, 23434, 48432); 11/12/2014 Copyright © SubMain 2014 Slide 18
  • 19. Example: Primitive Obsession // method call relying on primitives TransferFunds(23423, 23434, 48432); // refactored to be more clear and use higher level objects Account transferFrom = _accountRepository.Get(23423); Account transferTo = _accountRepository.Get(23434); var transferAmount = new Money(48432, Currency.USD); TransferFunds(transferFrom, transferTo, transferAmount); 3/25/2014 Copyright © SubMain 2014 Slide 19
  • 20. Primitive Obsession Common Examples Phone Numbers Social Security Numbers ZIP/Postal Codes Money Age Temperature Address Credit Card Information 3/25/2014 Copyright © SubMain 2014 Slide 20
  • 21. Code Smell: Data Clumps Sets of data items that are always used together, but are not organized together Similar to Primitive Obsession, but always deals with several items Frequently give rise to long parameter lists (another smell) 11/12/2014 Copyright © SubMain 2014 Slide 21
  • 22. Example: Data Clumps // data clumps on an order Order.CreditCardName = creditCardName; Order.CreditCardNumber = creditCardNumber; Order.ExpiresMonth = creditCardMonth; Order.ExpiresYear = creditCardYear; Order.SecurityCode = creditCardSecurityCode; 11/12/2014 Copyright © SubMain 2014 Slide 22
  • 23. Example: Data Clumps // data clumps on an order Order.CreditCardName = creditCardName; Order.CreditCardNumber = creditCardNumber; Order.ExpiresMonth = creditCardMonth; Order.ExpiresYear = creditCardYear; Order.SecurityCode = creditCardSecurityCode; // refactored by Extracting a new CreditCardInfo class CreditCardInfo cardInfo = new CreditCardInfo( creditCardNme, creditCardNumber, creditCardMonth, creditCardYear, creditCardSecurityCode); Order.CreditCard = cardInfo; 11/12/2014 Copyright © SubMain 2014 Slide 23
  • 24. Code Smell: Poor Names Names should: Be descriptive Be at appropriate abstraction level Use standard terms Be unambiguous Avoid encodings Describe side effects Be longer when scope is large 11/12/2014 Copyright © SubMain 2014 Slide 24
  • 25. Example: Poor Names public static List<int> Generate(int n) { var x = new List<int>(); for (int i = 2; n > 1; i++) for (; n % i == 0; n /= i) x.Add(i); return x; } 11/12/2014 Copyright © SubMain 2014 Slide 25
  • 26. Example: Poor Names public static List<int> GeneratePrimeFactorsOf(int input) { var primeFactors = new List<int>(); for (int candidateFactor = 2; input > 1; candidateFactor++) while (input % candidateFactor == 0) { primeFactors.Add(candidateFactor); input /= candidateFactor; } return primeFactors; } // Usage: var factors = GeneratePrimeFactorsOf(input); 11/12/2014 Copyright © SubMain 2014 Slide 26
  • 27. Example: Inappropriate Abstraction Level public class User { public string UserName { get; set; } public static int GetTotalUserCountInDatabaseTable() { throw new NotImplementedException(); } public static SqlDataReader GetDataReaderWithRoles(string userName) { throw new NotImplementedException(); } } 11/12/2014 Copyright © SubMain 2014 Slide 27
  • 28. Example: Inappropriate Abstraction Level public class User { public string UserName { get; set; } public IEnumerable<Role> IsInRoles() { throw new NotImplementedException(); } } 11/12/2014 Copyright © SubMain 2014 Slide 28 public class SqlUserRepository { public int TotalUserCount() { throw new NotImplementedException(); } public IEnumerable<Role> UserIsInRoles(string userName) { throw new NotImplementedException(); } }
  • 29. How CodeIt.Right Helps 11/12/2014 Copyright © SubMain 2014 29
  • 30. What is CodeIt.Right  Code Quality Analysis and Metrics  Automated Code Review process  Automated way to discover and fix code smells  Automatic and safe refactoring of issues into conforming code  Ensure your code adheres to (your) predefined design requirements and best coding practices 11/12/2014 Copyright © SubMain 2014 30
  • 31. What is CodeIt.Right - continued Instant Code Review – real-time code checking OnDemand Analysis Source Control Check-In Policy Build Process Integration Hundreds of rules  Security, Performance, Usage, Design, Maintainability, Exception Handling, Globalization, Async, and more 11/12/2014 Copyright © SubMain 2014 31
  • 32. Demo Discover and Fix Code Smells Coding Pattern Examples  ISerializable/Custom Serialization  Dispose/Finalize 11/12/2014 Copyright © SubMain 2014 32
  • 33. Q&A Questions? Email - customer-service@submain.com Video - submain.com/codeit.right/video Download the free CodeIt.Right trial at submain.com/codeit.right 11/12/2014 Copyright © SubMain 2014 33 1 (800) 936-2134 http://submain.com/webcasts/identify-and-correct-common-code-smells/ for the webcast recording and slides download