SlideShare a Scribd company logo
1 of 43
Top 5 Ways to Improve Your
Code
Eric De Carufel
Agile Coach

http://blog.decarufel.net
http://pyxis-tech.com
Introduction
• Legacy code is code without
  tests
  • Michael Feather in Working
    effectively with legacy code
• Without continuous
  maintenance the code will
  degrade rapidly
• We need to detect and
  remove code smell
My Top 5 Improvements
     1. Simplify conditionals
         2. Improve code documentation
              3. Improve method calls
                   4. Manage scope
                        5. Remove dead code
1. Simplify conditionals – Why?
•   Reduced complexity
•   Better readability
•   Better maintainability
•   Better reusability
1. Simplify conditionals –When?
•   There is more than one condition (and / or)
•   There is too much code in the body
•   The condition is based on type
•   There are nested if statements
•   There are many decisions based on the same info
    (if else if chain / switch case)
1. Simplify conditionals – How?
• Refactor conditional statements
   •   Decompose conditional code
   •   Consolidate conditional expressions
   •   Consolidate duplicate conditional fragments
   •   Introduce null objects
   •   Flatten nested if
   •   Don't use negative conditions
   •   Keep conditional statements lean
• Avoid conditional statements
   • Replace conditional code with polymorphism
   • Replace conditional logic with strategy
   • Replace conditional dispatchers with commands
Decompose Conditional Code
Consolidate Conditional Expressions
Consolidate Duplicate Conditional Fragments
Introduce Null Objects
Flatten Nested if
Don't Use Negative Conditions
Keep Conditional Statements Lean
• Do your best to have only one condition
   • Use methods to combine multiple conditions
• Invert your conditions if most (or all) the code of
  your method is inside the "true" block
   • Make sure to avoid double negation
Replace Conditional with Polymorphism
Replace Conditional Logic with Strategy
Replace Conditional Dispatcher with Command
2. Delete comments – Why?
• Better readability
• Better maintainability
• Fewer obsolete comments
2. Delete comments – When?
• Every time there is a comment that is not (useful)
  information, intention, clarification, warning, TODO or
  amplification.
• Comments are the only content of a code section
   • Empty catch statements
• Your comments describe line by line what you are trying to
  do
   • Example:
      // Getting connection string from configuration
      // Opening connection
      // Retrieving data
      // Closing connection
2. Delete comments – How?
• Replace comments with good naming
  • Extract methods
  • Use meaningful names
• Write useful comments
• Naming Conventions (MSDN: Guidelines for names)
  •   Properties
  •   Enums
  •   Events
  •   Methods
Extract Methods
Use Meaningful Names
•   Use Intention-Revealing names
•   Avoid disinformation
•   Make meaningful distinctions
•   Use pronounceable names
•   Avoid encoding
•   Avoid mental mapping
•   Class names -> nouns not verbs
•   Method names -> verbs
•   Don't be cute. Use standard names
•   Solution Domain Names vs Problem Domain Names
Properties
• Do use PascalCase naming
• Do name properties with a noun, noun phrase or an
  adjective
• Do Not use names that match Get method
• Do name booleans with Can, Is or Has prefix
Enums
• Consider the first element to be
  the default value
• Do use PascalCasing naming
• Single choice enumerations should
  be singular
• Bit fields enumerations should be
  plural and have Flags attibute
• Value of bit fields enumeration
  should be coherent (Read & Write
  == ReadWrite)
Events
• Do use PascalCase naming
• Do name event using a verb, present progressive for pre-event and past for post-event


• Do provide a virtual version of the event to override


• Do provide a way to cancel pre-event
Methods
• Do give methods names that are verbs or verb
  phrases
  • ProcessPayment
• Do express the return value in method name
  • CreateCustomer
  • GetInvoice
• Use consistent naming (Get, Fetch or Retrieve but
  not all in same context)
3. Clarify contracts – Why?
• Better performance
• Better readability
• Better reusability
3. Clarify contracts – When?
• There are too many parameters (how many is too
  many?)
• A method does more than one thing
• A method uses out parameters
• You need default values
3. Clarify contracts – How?
• Reduce number of parameters
  • Introduce parameter object
  • Create overloads with less parameters
  • Use default values
• Function output
  • Return type value
  • Use out parameters
• Overload methods in proper order
Introduce Parameter Object
Create Overloads with Fewer Parameters
Use Default Values
4. Reduce scope – Why?
• Avoid side effects
• Better reusability
• Better maintainability
4. Reduce scope – When?
• A field is used in only a few methods
• Public members expose class behavior
4. Reduce scope – How?
• Reduce visibility
   • Use protected
   • Use private
   • Use Internal
• Reduce scope
   • Move fields to method
   • Split class
   • Move local variable close to its use
• Reduce lifetime
   • Initialize late
   • Reduce references
   • Free early
5. Remove Dead Code – Why?
•   Because you must
•   Better maintainability
•   Better performance
•   Better readability
•   100% test coverage
5.Remove Dead Code – When?
• You know the code is dead
• You think the code is dead
• You want that code to be dead
5. Remove Dead Code – How?
• Identify and remove dead code
  • Delete the code
  • Compile
  • Run the tests
• What is dead code?
  • Commented code.
  • Any line of code that is not covered by unit tests.
• Tools
  • There are tools that delete all code not covered by unit tests.
Next Steps
• Improve your conditional code
• Improve your documentation
• Improve your method calls
Resources
   •   Refactoring – Improving the design of existing code
        •   Author: Martin Fowler
        •   Edition: Addison Wesley
        •   ISBN: 978-0-201-48567-7
   •   Refactoring to patterns (Martin Fowler signature)
        •   Author: Joshua Kerievsky
        •   Edition: Adison Wesley
        •   ISBN: 978-0-321-21335-1
   •   Clean code – a handbook of agile software craftsmanship
        •   Author: Robert C. Martin
        •   Edition: Prentice Hall
        •   ISBN: 978-0-132-35088-4
   •   Working effectively with legacy code
        •   Author: Michael C. Feather
        •   Edition: Prentice Hall
        •   ISBN: 978-0-13-117705-5
Related sessions
• Day 2 – 08h45 to 10h00
  • DEV373 – Testing with Microsoft Visuals Studio Test
    Professional and the new Team Lab 2010
    by Etienne Tremblay
• Day 2 – 10h30 to 11h45
  • ARC301 – Design by Contract (DbC) and Code
    Contracts in Visual Studio 2010
    by Joel Hebert
Remember To Complete Your Evaluations!
You could WIN a Samsung Focus
Windows Phone 7!
Let us know what you liked & disliked!
Remember, 1=Bad, 5=Good 
Please provide comments!
No purchase necessary. The contest is open to residents of Canada (excluding government employees). The Toronto Tech·Days evaluation form contest begins on October 25th, 2011 and
ends on October 26th, 2011. The Vancouver Tech·Days evaluation form contest begins on November 15th, 2011 and ends on November 16th, 2011. The Montreal Tech·Days evaluation
form contest begins on November 29th, 2011 and ends on November 30th, 2011. Participants can enter the contest in one of two ways: (1) complete and submit an evaluation form by the
contest close date; or (2) provide contact information by the contest close date. The draw for Toronto will take place on October 31st, 2011. The draw for Vancouver will take place on
November 21st, 2011. The draw for Montreal will take place on December 5th, 2011. The chances of being selected depend upon the number of eligible entries. Selected participants will be
contacted by phone and/or e-mail and will be required to answer correctly a time-limited skill-testing question. There are three (3) prizes available to be won. One (1) prize will be given away
for each Tech·Days event in Toronto (October 25-26 2011), Vancouver (November 15-16 2011) and Montreal (November 29-30 2011). The prize consists of a Samsung Focus Windows
Phone 7 (handset only; voice and/or data plan not included) (approximate retail value of $499 CAD). The prize will be delivered to the shipping address designated by the winner within 6-8
weeks. The winner may be required to sign a declaration and release form. For full contest rules, please see a Microsoft Tech·Days representative.


 You can email any additional comments directly to
        td_can@microsoft.com at any time.
Q&A
© 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should
                          not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.
                                                  MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related Content

Viewers also liked

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
The Evolution and Future of Content Publishing
The Evolution and Future of Content PublishingThe Evolution and Future of Content Publishing
The Evolution and Future of Content PublishingFITC
 
[Agile Testing Day] Techniques avancées de tests
[Agile Testing Day] Techniques avancées de tests[Agile Testing Day] Techniques avancées de tests
[Agile Testing Day] Techniques avancées de testsCellenza
 
L'analyse de code au service de la qualité
L'analyse de code au service de la qualitéL'analyse de code au service de la qualité
L'analyse de code au service de la qualitéStephane Leclercq
 

Viewers also liked (6)

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
The Evolution and Future of Content Publishing
The Evolution and Future of Content PublishingThe Evolution and Future of Content Publishing
The Evolution and Future of Content Publishing
 
[Agile Testing Day] Techniques avancées de tests
[Agile Testing Day] Techniques avancées de tests[Agile Testing Day] Techniques avancées de tests
[Agile Testing Day] Techniques avancées de tests
 
L'analyse de code au service de la qualité
L'analyse de code au service de la qualitéL'analyse de code au service de la qualité
L'analyse de code au service de la qualité
 
4D Summit2013 refactoring
4D Summit2013 refactoring4D Summit2013 refactoring
4D Summit2013 refactoring
 
Coder proprement
Coder proprementCoder proprement
Coder proprement
 

More from Eric De Carufel

Bracket Show Episode 35 - histoire de c# de 2002 à 2019
Bracket Show Episode 35 - histoire de c# de 2002 à 2019Bracket Show Episode 35 - histoire de c# de 2002 à 2019
Bracket Show Episode 35 - histoire de c# de 2002 à 2019Eric De Carufel
 
Architecture azure performante
Architecture azure performanteArchitecture azure performante
Architecture azure performanteEric De Carufel
 
Refactoring to Design Patterns
Refactoring to Design PatternsRefactoring to Design Patterns
Refactoring to Design PatternsEric De Carufel
 
Cqrs + event sourcing pyxis v2 - en
Cqrs + event sourcing   pyxis v2 - enCqrs + event sourcing   pyxis v2 - en
Cqrs + event sourcing pyxis v2 - enEric De Carufel
 
Top 5 des meilleures façons d'améliorer votre code
Top 5 des meilleures façons d'améliorer votre codeTop 5 des meilleures façons d'améliorer votre code
Top 5 des meilleures façons d'améliorer votre codeEric De Carufel
 
Dvcs mercurial - pyxis - eric de carufel
Dvcs   mercurial - pyxis - eric de carufelDvcs   mercurial - pyxis - eric de carufel
Dvcs mercurial - pyxis - eric de carufelEric De Carufel
 
Top 5 des meilleures façon d'améliorer ton code
Top 5 des meilleures façon d'améliorer ton codeTop 5 des meilleures façon d'améliorer ton code
Top 5 des meilleures façon d'améliorer ton codeEric De Carufel
 

More from Eric De Carufel (8)

Bracket Show Episode 35 - histoire de c# de 2002 à 2019
Bracket Show Episode 35 - histoire de c# de 2002 à 2019Bracket Show Episode 35 - histoire de c# de 2002 à 2019
Bracket Show Episode 35 - histoire de c# de 2002 à 2019
 
Architecture azure performante
Architecture azure performanteArchitecture azure performante
Architecture azure performante
 
Refactoring to Design Patterns
Refactoring to Design PatternsRefactoring to Design Patterns
Refactoring to Design Patterns
 
Cqrs + event sourcing pyxis v2 - en
Cqrs + event sourcing   pyxis v2 - enCqrs + event sourcing   pyxis v2 - en
Cqrs + event sourcing pyxis v2 - en
 
Top 5 des meilleures façons d'améliorer votre code
Top 5 des meilleures façons d'améliorer votre codeTop 5 des meilleures façons d'améliorer votre code
Top 5 des meilleures façons d'améliorer votre code
 
CQRS + Event Sourcing
CQRS + Event SourcingCQRS + Event Sourcing
CQRS + Event Sourcing
 
Dvcs mercurial - pyxis - eric de carufel
Dvcs   mercurial - pyxis - eric de carufelDvcs   mercurial - pyxis - eric de carufel
Dvcs mercurial - pyxis - eric de carufel
 
Top 5 des meilleures façon d'améliorer ton code
Top 5 des meilleures façon d'améliorer ton codeTop 5 des meilleures façon d'améliorer ton code
Top 5 des meilleures façon d'améliorer ton code
 

Recently uploaded

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Recently uploaded (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Top 5 ways to improve your code

  • 1. Top 5 Ways to Improve Your Code Eric De Carufel Agile Coach http://blog.decarufel.net http://pyxis-tech.com
  • 2. Introduction • Legacy code is code without tests • Michael Feather in Working effectively with legacy code • Without continuous maintenance the code will degrade rapidly • We need to detect and remove code smell
  • 3. My Top 5 Improvements 1. Simplify conditionals 2. Improve code documentation 3. Improve method calls 4. Manage scope 5. Remove dead code
  • 4. 1. Simplify conditionals – Why? • Reduced complexity • Better readability • Better maintainability • Better reusability
  • 5. 1. Simplify conditionals –When? • There is more than one condition (and / or) • There is too much code in the body • The condition is based on type • There are nested if statements • There are many decisions based on the same info (if else if chain / switch case)
  • 6. 1. Simplify conditionals – How? • Refactor conditional statements • Decompose conditional code • Consolidate conditional expressions • Consolidate duplicate conditional fragments • Introduce null objects • Flatten nested if • Don't use negative conditions • Keep conditional statements lean • Avoid conditional statements • Replace conditional code with polymorphism • Replace conditional logic with strategy • Replace conditional dispatchers with commands
  • 12. Don't Use Negative Conditions
  • 13. Keep Conditional Statements Lean • Do your best to have only one condition • Use methods to combine multiple conditions • Invert your conditions if most (or all) the code of your method is inside the "true" block • Make sure to avoid double negation
  • 14. Replace Conditional with Polymorphism
  • 15. Replace Conditional Logic with Strategy
  • 17. 2. Delete comments – Why? • Better readability • Better maintainability • Fewer obsolete comments
  • 18. 2. Delete comments – When? • Every time there is a comment that is not (useful) information, intention, clarification, warning, TODO or amplification. • Comments are the only content of a code section • Empty catch statements • Your comments describe line by line what you are trying to do • Example: // Getting connection string from configuration // Opening connection // Retrieving data // Closing connection
  • 19. 2. Delete comments – How? • Replace comments with good naming • Extract methods • Use meaningful names • Write useful comments • Naming Conventions (MSDN: Guidelines for names) • Properties • Enums • Events • Methods
  • 21. Use Meaningful Names • Use Intention-Revealing names • Avoid disinformation • Make meaningful distinctions • Use pronounceable names • Avoid encoding • Avoid mental mapping • Class names -> nouns not verbs • Method names -> verbs • Don't be cute. Use standard names • Solution Domain Names vs Problem Domain Names
  • 22. Properties • Do use PascalCase naming • Do name properties with a noun, noun phrase or an adjective • Do Not use names that match Get method • Do name booleans with Can, Is or Has prefix
  • 23. Enums • Consider the first element to be the default value • Do use PascalCasing naming • Single choice enumerations should be singular • Bit fields enumerations should be plural and have Flags attibute • Value of bit fields enumeration should be coherent (Read & Write == ReadWrite)
  • 24. Events • Do use PascalCase naming • Do name event using a verb, present progressive for pre-event and past for post-event • Do provide a virtual version of the event to override • Do provide a way to cancel pre-event
  • 25. Methods • Do give methods names that are verbs or verb phrases • ProcessPayment • Do express the return value in method name • CreateCustomer • GetInvoice • Use consistent naming (Get, Fetch or Retrieve but not all in same context)
  • 26. 3. Clarify contracts – Why? • Better performance • Better readability • Better reusability
  • 27. 3. Clarify contracts – When? • There are too many parameters (how many is too many?) • A method does more than one thing • A method uses out parameters • You need default values
  • 28. 3. Clarify contracts – How? • Reduce number of parameters • Introduce parameter object • Create overloads with less parameters • Use default values • Function output • Return type value • Use out parameters • Overload methods in proper order
  • 30. Create Overloads with Fewer Parameters
  • 32. 4. Reduce scope – Why? • Avoid side effects • Better reusability • Better maintainability
  • 33. 4. Reduce scope – When? • A field is used in only a few methods • Public members expose class behavior
  • 34. 4. Reduce scope – How? • Reduce visibility • Use protected • Use private • Use Internal • Reduce scope • Move fields to method • Split class • Move local variable close to its use • Reduce lifetime • Initialize late • Reduce references • Free early
  • 35. 5. Remove Dead Code – Why? • Because you must • Better maintainability • Better performance • Better readability • 100% test coverage
  • 36. 5.Remove Dead Code – When? • You know the code is dead • You think the code is dead • You want that code to be dead
  • 37. 5. Remove Dead Code – How? • Identify and remove dead code • Delete the code • Compile • Run the tests • What is dead code? • Commented code. • Any line of code that is not covered by unit tests. • Tools • There are tools that delete all code not covered by unit tests.
  • 38. Next Steps • Improve your conditional code • Improve your documentation • Improve your method calls
  • 39. Resources • Refactoring – Improving the design of existing code • Author: Martin Fowler • Edition: Addison Wesley • ISBN: 978-0-201-48567-7 • Refactoring to patterns (Martin Fowler signature) • Author: Joshua Kerievsky • Edition: Adison Wesley • ISBN: 978-0-321-21335-1 • Clean code – a handbook of agile software craftsmanship • Author: Robert C. Martin • Edition: Prentice Hall • ISBN: 978-0-132-35088-4 • Working effectively with legacy code • Author: Michael C. Feather • Edition: Prentice Hall • ISBN: 978-0-13-117705-5
  • 40. Related sessions • Day 2 – 08h45 to 10h00 • DEV373 – Testing with Microsoft Visuals Studio Test Professional and the new Team Lab 2010 by Etienne Tremblay • Day 2 – 10h30 to 11h45 • ARC301 – Design by Contract (DbC) and Code Contracts in Visual Studio 2010 by Joel Hebert
  • 41. Remember To Complete Your Evaluations! You could WIN a Samsung Focus Windows Phone 7! Let us know what you liked & disliked! Remember, 1=Bad, 5=Good  Please provide comments! No purchase necessary. The contest is open to residents of Canada (excluding government employees). The Toronto Tech·Days evaluation form contest begins on October 25th, 2011 and ends on October 26th, 2011. The Vancouver Tech·Days evaluation form contest begins on November 15th, 2011 and ends on November 16th, 2011. The Montreal Tech·Days evaluation form contest begins on November 29th, 2011 and ends on November 30th, 2011. Participants can enter the contest in one of two ways: (1) complete and submit an evaluation form by the contest close date; or (2) provide contact information by the contest close date. The draw for Toronto will take place on October 31st, 2011. The draw for Vancouver will take place on November 21st, 2011. The draw for Montreal will take place on December 5th, 2011. The chances of being selected depend upon the number of eligible entries. Selected participants will be contacted by phone and/or e-mail and will be required to answer correctly a time-limited skill-testing question. There are three (3) prizes available to be won. One (1) prize will be given away for each Tech·Days event in Toronto (October 25-26 2011), Vancouver (November 15-16 2011) and Montreal (November 29-30 2011). The prize consists of a Samsung Focus Windows Phone 7 (handset only; voice and/or data plan not included) (approximate retail value of $499 CAD). The prize will be delivered to the shipping address designated by the winner within 6-8 weeks. The winner may be required to sign a declaration and release form. For full contest rules, please see a Microsoft Tech·Days representative. You can email any additional comments directly to td_can@microsoft.com at any time.
  • 42. Q&A
  • 43. © 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes

  1. DO NOT REMOVE THIS SLIDE
  2. DO NOT REMOVE THIS SLIDE