Caring about Code Quality


Published on

We all have seen our share of bad code. We certainly have come across some good code as well. What are the characteristics of good code? How can we identify those? What practices can promote us to write and maintain more of those good quality code. This presentation will focus on this topic that has a major impact on our ability to be agile and succeed.

Published in: Technology
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Caring about Code Quality

  1. 1. CARING ABOUT CODE QUALITYspeaker.identity { name Venkat Subramaniam company Agile Developer, Inc. credentials Programmer, Author, Trainer blog email}
  2. 2. AbstractWe all have seen our share of bad code. We certainlyhave come across some good code as well. What are thecharacteristics of good code? How can we identifythose? What practices can promote us to write andmaintain more of those good quality code. Thispresentation will focus on this topic that has a majorimpact on our ability to be agile and succeed.Characteristics of quality codeMetrics to measure qualityWays to identify and build quality 2
  3. 3. Why care about Code Quality? You can’t be Agile if your Code sucks 3
  4. 4. Code Quality 4
  5. 5. Change in Requirements[LARM03] 5
  6. 6. Cost of Defect 100 Cost 80 tocorrect a 60defect 40 20 0 Requirements Design Code Test Operation [BOEH01] 6
  7. 7. Magnitude of Computational ProblemEuropean Space Agency took 10 years and $8 billion dollars to developAriane 5On June 4, 1996, it took its first voyage with $500 million cargoIn 40 seconds its inertial reference system failed64-bit floating point number representing the horizontal velocity ofthe rocket was converted into 16-bit signed integer—conversion failedbecause of overflowVehicle was deliberately destroyed for safety 7
  8. 8. Major MisfiresSeptember 1999: Metric mishap causes loss of NASAorbiter [CNN99]March 2001: Nike i2 Forecast System found to beinaccurate–Nike takes inventory write-off [CIO03]August 2004: NASA: DOS Glitch Nearly Killed MarsRover–Story on Spirit: “...The flaw, since fixed, was only discovered after days ofagonizingly slow tests...“ [EXTR04]June 2007: United flights grounded by computer glitch[COMP07]... 8
  9. 9. Software Defect Reduction Top 10 List Finding, fixing problem in production is 100 times more expensive than during requirements/design phase. 40-50% of effort on projects is on avoidable rework. ~80% of avoidable rework comes from 20% of defects. ~80% of defects come from 20% of modules; about half the modules are defect free. ~90% of downtime comes from at most 10% of defects.[BOEH01] 9
  10. 10. Software Defect Reduction Top 10 List Peer reviews catch 60% of defects. Perspective-based reviews catch 35% more defects than nondirected reviews. Disciplined personal practices can reduce defect introduction rates by up to 75%. costs 50% more per source instruction to develop high-dependability software product... ~40-50% of user programs have nontrivial defects.[BOEH01] 10
  11. 11. But, Still...The evidence is overwhelming, but still...We never seem to have time to do it, but always seemfind time to redo it?! 11
  12. 12. What’s Quality?Measure of how well the software is designed andimplementedQuality is subjective 12
  13. 13. Why care, there’s QA?! Can’t QA take care of quality, why should developers care? QA shouldn’t care about quality of design and implementation They should care about acceptance, performance, usage, and relevance of the application Give them a better quality software so they can really focus on that“Lowering Quality Lengthens Development Time”—First Law of Programming 13
  14. 14. More Maintenance... You’ll do more maintenance if quality is better Why? It’s easier to accommodate change, so you can be flexible and relevant “Maintenance is a solution, not a problem” “Better methods lead to more maintenance, not less”[GLAS03] 14
  15. 15. Pay your Technical DebtTechnical debt are activities (like refactoring,upgrading a library, conforming to some UI or codingstandard, ...) that you’ve left undoneThese will hamper your progress if left undone for alonger time 15
  16. 16. Measuring QualityHard to measureNeed to find useful metricsExample of wrong metric: Lines-Of-Code (LOC) Is more code better or worse? You can produce more code? You needed that much code for that? 16
  17. 17. Measuring Quality...Highly subjectiveHighly qualitativeIs the code readable, understandable?Is the code verbose?Variable/method names that are meaningfulSimple code that worksDoes it have tests? What’s the coverage? 17
  18. 18. Ways to Improve Quality Start early Don’t Compromise Schedule time to lower your technical debt Make it work; make it right (right away) Requires monitoring and changing behavior Be willing to help and be helped Devise lightweight non-bureaucratic measures 18
  19. 19. Individual EffortsWhat can you do?Care about design of your code Good names for variables, methods, ... Short methods, smaller classes, ... Learn by reading good codeKeep it SimpleWrite tests with high coverageRun all your tests before checkinCheckin Frequently 19
  20. 20. Individual EffortsLearn your languageIf you’re switching languages or using multiplelanguages, know the differencesAvoid Cargo cult programming–following rituals, styles,principles, or structure that serves no real purposeCourt feedback and criticism 20
  21. 21. Keep It Simple!Don’t build Rube Goldberg Machines–something complexto do simple things 21
  22. 22. Keep It Simple!“There are two ways of constructing a softwaredesign. One way is to make it so simple that thereare obviously no deficiencies. And the other way isto make it so complicated that there are no obviousdeficiencies,”–C.A.R. Hoare. 22
  23. 23. Team EffortsAvoid shortcutsTake collective ownership–Team should own the codePromote positive interactionProvide constructive feedbackConstant code review 23
  24. 24. You said Code Review?Code review is by far the proven way to reduce codedefects and improve code qualityBut, code review does not work?It depends on how it’s done 24
  25. 25. If code review is...Do you get together as a team, project code, andreview?At least three problems? You hate being critiqued that way You’d much rather write more code in that time Project manager says “last time you guys got together for review, fight ensued and one guy quit, no more code reviews for you...”Don’t make it an emotionally draining 25
  26. 26. Seeking and Receiving FeedbackWe’ve used code review very effectivelyCode reviewed by one developer right after task iscomplete (or anytime before)Rotate reviewer for each reviewSay positive things, what you really likeConstructively propose changesInstead of “that’s lousy long method” say, “why don’tyou split that method...” 26
  27. 27. Tactical Continuous ReviewReview not only code, but also testsDo not get picky on style, instead focus on correctness,readability, design, ...“Code Review makes me a Hero or makes me Smarter,”– Brian C. 27
  28. 28. Value of Review“Rigorous inspection can remove up to 90 percent oferrors before the first test case is run.”“Reviews are both technical and sociological, and bothfactors must be accommodated.”[GLAS03] 28
  29. 29. Broken Window Problem Study shows broken windows lead to vandalism Code that no one cares for deteriorates quickly Do not tolerate your code being trashed Fix code that’s not elegant or looks broken Keep your code always releasable [SUBR06][FIBW, THOM99] 29
  30. 30. Treat Warning as ErrorsDon’t say “that’s only a warning”Warnings may have hidden problemsThey’re annoying and distractingUse compiler options to treat warnings as errorsIf unavoidable, suppress (selectively) 30
  31. 31. CohesionThe code is focused, narrow, smallIt does one thing and one thing wellSingle Responsibility PrincipleHigher cohesion -> Lower Cyclomatic Complexity (seelater)Strive for higher cohesion At method, class, component, subsystem level 31
  32. 32. Extensibility and Flexibility You build abstraction, hierarchy, ... to make your code extensible Extensibility is an anticipation What if the requirement does not meet what you anticipated? You have more code to work with and it is hard to extend in the new direction because of that Predicting is hard 32
  33. 33. Triangulation Postpone generalization Wait for code to evolve a bit You see evidence of what’s needed and generalize based on real use But, won’t that be expensive? Changes will require less work since you have lesser code to deal with[Beck02] 33
  34. 34. Cohesion and Cost of Change Code that’s doing too many things is hard to maintain Developer who must make change has to understand lots of things Code is complex, has higher cyclomatic complexity Your change likely will break something else Smaller, cohesive code is less expensive to maintain 34
  35. 35. Code CoverageHow much (%) of your code is covered by test?How about paths through your codeIs there code that deserve not to be tested?Instrumentation tools can tell you which and how muchcode is coveredTools: [Java] JCover, Cobertura, ... [.NET] NCover,... [C++] C++ Test Coverage Tool, Bullseye Coverage, CTC++,Visual Studio, ...Tools like Guantanamo and Ashcroft delete code thathave no test! 35
  36. 36. Code CoverageCode Test Coverage Tells you how much of your code’s exercised Does not tell you about test quality, however 36
  37. 37. ComplexityLong methods cause painPaths in codeUnnecessary and stale comments cause confusionLarge classes are hard to maintain... 37
  38. 38. Cyclomatic ComplexityThomas McCabe’sCounts distinct paths through codeNumber of decision points + 1# of edges - # of nodes + 2Cyclomatic Complexity Number (CCN) > 10 is riskyStrive for lower countConsider refactoring and fortify your testsTools: [Java] JavaNCSS, PMD, CheckStyle, ... [.NET] FxCop,Visual Studio Code Analyzer, Resharper, NDepend, ... [C++]Code Counter, CMT++, Cyclo, ... 38
  39. 39. Cyclomatic ComplexityFor your tests to have reasonable code coverage:# of tests > CCN 39
  40. 40. Cyclomatic ComplexityCyclomatic Complexity Number Gives an indication of degree of hardness Does not indicate degree of defect 40
  41. 41. Code SizeAddresses problems arising from large, low cohesivecodeCode Size Rules check for the size of code and flags if itexceedsHow small is smallCode must fit into a screen (without lowering font size)[about 15 to 20 statements per method] 41
  42. 42. Code DuplicationDuplicated code is expensive to maintainHard to fix bugs, hard to make enhancementsWhy do we duplication code then?Path of least resistance–you’re not breaking existingcode, right?What to do? Identify and extract methodsTools: [Java] PMD, ... [.NET] Simian, ... [C++] ...Tools: Simian, StrictDuplicateCode, ... 42
  43. 43. Assessing RiskComplexity Automated Tests Risk Low Low High Low High Low High Low HIGH High High Medium 43
  44. 44. C.R.A.P MetricChange Risk Analysis and Prediction (CRAP) Experimental metrics and toolMeasures effort and risk to maintain legacy codeUses Cyclomatic Complexity (comp) and code coverage (cov)Created by Bob Evans and Alberto Savoia of Agitar [SAVO07]For a method m, Version 0.1 of the formula isCRAP(m) = comp(m)^2 * (1-cov(m)/100)^3 + comp(m)Lower value => low change and maintenance riskLowest value 1. With no tests, risk increases as square ofcomplexity 44
  45. 45. C.R.A.P Metric 45
  46. 46. C.R.A.P Metric 30 = threshold for crappiness A complex method (within 30 CCN) can stay below the threshold with adequate tests CRAP Load: work estimate to address crappiness CRAP Load N means indicates the number of tests you need to write to bring your project below the thresholdcrap4J is an experimentation tool to measure this metric 46
  47. 47. Test QualityLow coverage indicates inadequate testHigher coverage does not mean adequate test, howeverHow good is the quality of test?Did you cover different conditions, boundaries, ...Mutating testers can help determine that[Java] Jester[.NET] Nester[C++] ? 47
  48. 48. Code DuplicationCode duplication is commonIncreases maintenance costMakes it hard to fix bugs and make enhancements[Java] Simian, PMD (Copy Paste Detector), ...[.NET] Simian, ...[C++] Simian, ... 48
  49. 49. Code AnalysisAnalyzing code to find bugsLook for logic errors, coding guidelines violations,synchronization problems, data flow analysis, ...[Java] PMD, FindBugs, JLint, ...[.NET] VS, FxCop, ...[C++] VS, Lint, ... 49
  50. 50. Identifying Problem "It was on one of my journeys between the EDSAC room and the punching equipment that…the realization cameover me with full force that a good part of the remainder of my life was going to be spent in finding errors in my own programs,"—Maurice V. Wilkes, pioneer in early machine design and microprogramming. 50
  51. 51. What is Code Smell?It’s a feeling or sense that something is not right in thecodeYou can’t understand itHard to explainDoes some magic 51
  52. 52. Code Smells Improper use of inheritanceDuplicationUnnecessary complexity Convoluted codeUseless/misleading comments Tight couplingLong classes Over abstractionLong methods Design Pattern overusePoor naming Trying to be cleverCode that’s not used ... 52
  53. 53. What? 53
  54. 54. Dealing with Code SmellKeep an eye on itIndicates code that needs either refactoring or someserious redesignTechnical DebtTake effort to clear the air–frequently 54
  55. 55. From Writing to Coding…William Zinsser Wrote “On Writing Well” 25 yearsago!He gives good principles for writing wellThese principles apply to programming as much aswriting non-fiction Simplicity Clarity Brevity Humanity 55
  56. 56. Clear, not Clever Don’t be clever, instead be clear“I never make stupid mistakes. Only very, very clever ones,”—Dr Who 56
  57. 57. No RushDon’t code in a Hurry—”Haste is Waste”Take time to read the code and see if is what you meantTake the time to write tests—make sure the code doeswhat you meant, not what you typedCode defensively“Act in haste and repent at leisure: Code too soon and debug forever,”—Raymond Kennington. 57
  58. 58. Commenting and Self-Documenting CodeLots of comments are written to coverup bad codeComments should say Why or purpose, not howDon’t comment what a code does—I can read the codefor that—keep it DRYDon’t keep documentation separate from code Use javadoc (Java), doxygen (C++), NDoc (C#),... At least provide a pointer to where it isIf you copy and paste, check if comments are stillrelevant 58
  59. 59. Commenting and Self-Documenting CodeDon’t use variable names that are cryptic or too briefKeep code simpleKeep code smallKeep comments minimum and meaningfulGive names for constants order(CoffeeSize.LARGE) instead of order(3) // large 59
  60. 60. Commenting and Self-Documenting CodeUse Assertions to document assumptionsDocument unique, special, or unexpected conditionsKeep them short and clear, howeverDon’t pour emotions and argumentsKeep an eye for stale comments 60
  61. 61. Code for Clarity—self-documenting...Can someone who does not know English still understandyour code?Can someone who does not speak your language stillunderstand your code?Some languages and frameworks are being created byexperts who don’t speak English as their first languageRuby - JapanGroovy - European and US collaborators 61
  62. 62. Comments on CommentingJustify violation of good programming practices or styles If you’ve to use some convoluted logic, unroll a loop, ... drop a comments to say why Will avoid unnecessary refactoring attempt only to discover that it has to stay that way Will help check if the assumptions stated are still validDon’t comment clever code, rewrite itIf everyone stumbles on a particular problem, don’t commentto caution, instead fix it 62
  63. 63. Error In Your FaceRaise exceptions so they’re in your faceDon’t let problems slip byAlso, if it is hard to locate problems duringdevelopment, it will only get worse for your supportFind easy ways to identify what’s wrongLog is good, but provide a code to easily located therelevant message in it 63
  64. 64. SummaryPractice tactical peer code reviewConsider untested code is unfinished codeMake your code coverage and metrics visibleDon’t tolerate anyone trashing your codeWrite self documenting code and comment whysUse tools to check code qualityUse tools continuously—that is automatedTreat warnings as errorsKeep it smallKeep it simple 64
  65. 65. References[Beck02] "Test Driven Development: By Example," by Kent Beck, Addison Wesley, 2002.[BLOC05] "Java Puzzlers: Traps, Pitfalls, and Corner Cases," by Joshua Bloch, Neal Gafter,Addison Wesley, 2005.[BOEH01] "Software Defect Reduction Top 10 List," by Barry Boehm and Victor R. Basili,IEEE Computer, January 2001. ([GLAS03] "Facts and Fallacies of Software Engineering," by Robert L. Glass, Addison-Wesley, 2003.[FIBW] "Fixing Broken Windows," on Wikipedia ([THOM99] "The Pragmatic Programmer: From Journeyman to Master," by Andy Huntand Dave Thomas, Addison-Wesley, 2000 (Excerpt on Software Entropy and BrokenWindow Problem can be found at You can download examples and slides from - download 65