Readable code - available without prescription

Readable code - available without prescription

This talk tells the story of a revolution in the world of linguistics and how we can apply it to software development. Everyone agrees on the importance of readable code, but no-one can agree on how to write it. There are many conflicting rules out there, and they are all opinionated and arbitrary. Grammar is also full of rules, and not all rules are the same. “Prescriptive” rules are hard to follow. “Descriptive” rules are intuitive. With the help of Shakespeare, Noam Chomsky and some little green men, we will learn the dangers of prescriptive rules, and discover howreadable.com, an online scientific experiment that can help us write readable code.

Presented at FrontCon 2020
https://2020.frontcon.com/sessions/readable-code-available-without-prescription/

1a93f6606abdcf0ec6a850df9e4b830d?s=128

Daniel van Berzon

August 14, 2020
Tweet

Transcript

  1. Daniel van Berzon @ocastahq ocasta.com @dvberzon vanberzon.com Readable code (Available

    without prescription)
  2. Grammar

  3. None
  4. “Rachel and me went to the cinema” “Rachel and I

    went to the cinema” A B C
  5. Readable Code

  6. None
  7. A B C const sorted = input .split('') .sort() .join('');

    const chars = input.split(''); const sortedChars = chars.sort(); const sorted = sortedChars.join('');
  8. Grammar Readable Code

  9. .com

  10. Readable Code

  11. Writing code On your own For the computer Student

  12. Reading code Collaborating For developers Professional Reading : Writing 10

    : 1 - Robert C Martin
  13. Student Professional Cool Clever Efficient Succinct Exciting Clear Simple Intuitive

    Structured Boring write_code => => read_code
  14. … is hard to write Code that is easy to

    read
  15. const = 0; z Too Many Options

  16. Spoilers

  17. Other People

  18. const postcodeValid = (params) => { return strPresent(params.postcode); } const

    validateParams = (params) => { return firstNameValid(params) && lastNameValid(params) && emailValid(params) && postcodeValid(params); } Whitespace Indentation Break up long lines Legible Code ≠ Readable Code Easier on the eye?
  19. Readability Structure Consistency Brevity Convention Syntax Naming Clarity Approach

  20. Rules? Structure Consistency Brevity Convention Syntax Naming Clarity Approach

  21. Grammar

  22. Grammar English !"#$ %&'( )*+, -.

  23. Grumpy Language Teacher

  24. "Never end a sentence with a preposition!"

  25. What is he on about? preposition About what is he

    on? On about what is he? /
  26. “Rachel and me went to the cinema” “Rachel and I

    went to the cinema” A B C
  27. B: Rachel and I went to the cinema 2 words

    for referring to oneself “I” (subject): “I went to the cinema” “Me” (object): "Rachel noticed me” “Rachel” and “I” are both subjects “Rachel and I went to the cinema” So there!!
  28. 1. Opinion 2. Size 3. Age 4. Shape 5. Colour

    6. Origin 7. Material 8. Purpose English has complex grammar rules … Adjective order Green little men Little green men
  29. 1. Opinion 2. Size 3. Age 4. Shape 5. Colour

    6. Origin 7. Material 8. Purpose English has complex grammar rules … Adjective order Green little men Little green men lovely little old long green French silver serving spoon
  30. No one was ever taught this rule in school! Little

    green men Rachel and me went to the cinema Between you and I All debts are cleared between you and I Merchant of Venice Act 3 scene 2
  31. ? Little green men Rachel and I

  32. Noam Chomsky Universal Grammar Humans are born with an instinctive

    understanding of grammar. Prescriptive grammar Descriptive grammar
  33. Prescriptive grammar rule Arbitrary rule that prescribes how people should

    speak Robert Lowth 1710 - 1787 Rachel and I went to the cinema
  34. Descriptive grammar rule Instinctive grammar rule that describes how people

    speak naturally Mark Forsyth 1977 - present
  35. Prescriptive Descriptive Vs. Rachel and I went to the cinema

    How people Should speak How people speak naturally
  36. Readable Code?

  37. Learning code readability Psychology of code readability Make your code

    easier to read with Functional Programming Google JavaScript Style Guide Idiomatic.js Rules Code Readability Literature
  38. // bad function sayHi(name) { return 'How are you, '

    + name + '?'; } // good function sayHi(name) { return `How are you, ${name}?`; } Airbnb JavaScript Style Guide: Template strings give you a readable, concise syntax ... “ ”
  39. Prescriptive

  40. Prescriptive • Arbitrary • Opinions as facts • No evidence

  41. Prescriptive Descriptive

  42. Readable code (Available without prescription) 0

  43. No native speakers of: JavaScript Python C / C++ Ruby

    Java Universal grammar applies to native language speakers Flaw in the metaphor Baṣa Jawa
  44. Descriptive rules beneficial?

  45. Descriptive rules beneficial?

  46. Descriptive rules? • Based on empirical evidence • Describe how

    developers read / write code • Based on behaviour rather than opinion Ask a developer how readable they find code Measure how easily they can read code
  47. Niall Coleman Clarke - Daniel van Berzon - Jake 'Sid'

    Smith
  48. Online experiment to find descriptive rules for code readability Measures

    readability of coding constructs Showing code snippets to developers Measuring how easily they read them .com
  49. Metric for readability? Can a developer predict output of code?

    Time it takes them to understand the code
  50. None
  51. None
  52. None
  53. None
  54. Methodology

  55. A B C const sorted = input .split('') .sort() .join('');

    const chars = input.split(''); const sortedChars = chars.sort(); const sorted = sortedChars.join('');
  56. Chaining a.b.c x = a.b x.c Methodology

  57. Chaining a.b.c x = a.b x.c Methodology

  58. Chaining a.b.c x = a.b x.c Methodology

  59. Chaining 75% 50% } } a.b.c x = a.b x.c

    Methodology
  60. 11 Experiments Each testing a different coding construct 6 Exercises

    chaining methods
  61. function sort(input) { var lowerCase = input.toLowerCase(); var lettersArray =

    lowerCase.split(''); var sorted = lettersArray.sort(); return sorted.join(''); } var result = sort('bag'); function sort(input) { return input .toLowerCase() .split('') .sort() .join(''); } var result = sort('bag'); Participant asked to predict value of result ES5? Chaining vs Intermediate
  62. 545 participants 10+ 6-10 5 4 3 2 1 <1

    Years programming Main language Other Go Clojure Kotlin Swift HTML/CSS Python Typescript Ruby C# Java PHP JavaScript
  63. Results

  64. Chaining vs Intermediate 89.2% 93.8% 30.5s 39.3s Statistical analysis

  65. Chi-Squared test Welch's T-test P value P < 0.05 Chaining

    vs Intermediate
  66. P = 0.044 P = 0.001 Chaining vs Intermediate 89.2%

    93.8% 30.5s 39.3s
  67. function sort(input) { var lowerCase = input.toLowerCase(); var lettersArray =

    lowerCase.split(''); var sorted = lettersArray.sort(); return sorted.join(''); } var result = sort('bag'); function sort(input) { return input .toLowerCase() .split('') .sort() .join(''); } var result = sort('bag'); Chaining vs Intermediate
  68. Constructs: Chaining methods Operator precedence If statements Pure functions Abstraction

    Boolean algebra Naming Ternary operators Inline functions Early return Comments P value too high
  69. High P value? • No effect to measure • Effect

    too small • Sample size is too low • Flaw in methodology
  70. 8/2*(2+2) (8/2)*(2+2) =16 8/(2*(2+2)) =1 Operator precedence Operator precedence

  71. Precedence vs Brackets var fixed = 200; var monthly =

    20; var result = fixed + (monthly * 12); var fixed = 200; var monthly = 20; var result = fixed + monthly * 12;
  72. 91.7% 97.2% 19.1s 17.0s P = 0.014 P = 0.042

    Precedence vs Brackets
  73. var fixed = 200; var monthly = 20; var result

    = fixed + (monthly * 12); var fixed = 200; var monthly = 20; var result = fixed + monthly * 12; Precedence vs Brackets
  74. var result = fixed + (monthly * 12); var result

    = fixed + monthly * 12; An opinionated code formatter
  75. Order of if statements Prefer dealing with the positive case

    first instead of the negative. if (yes) { // foo } else { // bar } if (no) { // bar } else { // foo }
  76. Positive vs Negative branch first function canLegallyDrink(age) { var legal

    = age >= 18; if (legal) { return 'yes'; } else { return 'no'; } } var result = canLegallyDrink(14); function canLegallyDrink(age) { var legal = age >= 18; if (!legal) { return 'no'; } else { return 'yes'; } } var result = canLegallyDrink(14);
  77. !a && !b === !(a || b) Boolean Algebra Expanded

    vs Simplified
  78. Full results and recommendations https://howreadable.com

  79. Future

  80. Limitations of experiment • Code snippets have to be self

    contained and small • Exercises are not realistic • Larger scale factors impossible to test Consistency - Structure - Approach • Metrics are too simplistic
  81. Improvements • Explore different methodologies - Ask developers change code

    • Increase participation: 1000+ • Alternative approach?
  82. Analysis of existing code Linguistic research by searching a language

    corpus https://books.google.com/ngrams
  83. Get help ... and funding.

  84. Takeaways • Descriptive > Prescriptive • Possible to objectively measure

    readability • Question arbitrary rules • Science is hard! • Help us! info@howreadable.com
  85. Thank Jake 'Sid' Smith Niall Coleman Clarke Narani van Laarhoven

    Freyja Nash Phil Teare Cian Campbell Oskar Holm Daniel van Berzon @dvberzon vanberzon.com howreadable.com you @ocastahq ocasta.com