Readable code - Available without Prescription

Readable code - Available without Prescription

Grammar is all about rules, but not all rules are the same. This talk tells the story of a revolution in the world of linguistics and how we can apply it to software development.

With the help of Shakespeare, Noam Chomsky and some little green men, we will learn the dangers of prescriptive rules, and discover how an amateur online scientific experiment could help us write readable code.

Presented at Halfstack London 2019
https://halfstackconf.com/london

1a93f6606abdcf0ec6a850df9e4b830d?s=128

Daniel van Berzon

November 22, 2019
Tweet

Transcript

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

    without prescription)
  2. Grammar

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

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

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

    const chars = input.split(''); const sortedChars = chars.sort(); const sorted = sortedChars.join('')
  6. Grammar Readable Code Spanish Dutch Politics Photography Magic Singing Guilbert

    & Sullivan FC Barcelona Cheese Flamenco Film Popular Science
  7. Grammar Readable Code

  8. .com

  9. Readable Code

  10. Writing code On your own For the computer Student

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

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

    Structured Boring write_code => => read_code
  13. const = 0; • Too many options • Spoilers •

    Other people … is hard to write Code that is easy to read z
  14. 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?
  15. Readability Structure Consistency Brevity Convention Syntax Naming Clarity Approach

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

  17. Grammar

  18. Grumpy English Teacher

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

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

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

    went to the cinema” A B C
  22. B: Rachel and I went to the cinema 2 pronouns

    for referring to oneself “I” as subject: “I went to the cinema” “Me” as object: "Rachel noticed me” “Rachel” and “I” are both subjects “Rachel and I went to the cinema” Q.E.D. !!
  23. 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
  24. 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
  25. 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
  26. ? Little green men Rachel and I

  27. Noam Chomsky Universal Grammar Humans are born with an innate

    understanding of grammar. Prescriptive grammar Descriptive grammar
  28. Prescriptive Descriptive Arbitrary grammar rule that prescribes the way people

    should speak Vs. Innate grammar rule that describes the way people speak naturally Robert Lowth 1710 - 1787 Rachel and I went to the cinema Mark Forsyth 1977 - present
  29. Readable Code?

  30. 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
  31. // 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 ... “ ”
  32. Prescriptive • Arbitrary • Opinions as facts • No evidence

  33. Prescriptive Descriptive

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

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

  36. Descriptive rules beneficial?

  37. 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
  38. Niall Coleman Clarke - Daniel van Berzon - Jake 'Sid'

    Smith
  39. 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
  40. Metric for readability? Can a developer predict output of code?

    Time it takes them to understand the code
  41. None
  42. None
  43. None
  44. None
  45. Chaining a.b.c x = a.b x.c Methodology

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

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

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

    chaining methods
  49. 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
  50. 545 participants 10+ 6-10 5 4 3 2 1 <1

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

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

  53. Chi-Squared test Students T-test P value P < 0.05 Chaining

    vs Intermediate
  54. Chaining vs Intermediate 89.2% 93.8% 30.5s 39.3s

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

    93.8% 30.5s 39.3s
  56. 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
  57. Naming There are only two hard things in Computer Science:

    cache invalidation and naming things. - Phil Karlton
  58. array.filter(fn) Filtrate Residue

  59. Generic vs Specific naming function sortAlphabetically(str) { return str .split('')

    .sort() .join(''); } var result = sortAlphabetically('made'); function processStr(str) { return str .split('') .sort() .join(''); } var result = processStr('made');
  60. Generic vs Specific naming 95.3% 97.6% 18.7s 19.9s P =

    0.045 P = 0.125
  61. High P value? • No effect to measure Specific naming

    has no affect on time taken to read the code • Effect too small • Sample size is too low • Flaw in methodology
  62. Constructs: Chaining methods Operator precedence Pure functions Abstraction Boolean algebra

    If statements Naming Ternary operators Inline functions Early return Comments
  63. 8/2*(2+2) (8/2)*(2+2) =16 8/(2*(2+2)) =1 Operator precedence Operator precedence

  64. 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;
  65. 91.7% 97.2% 19.1s 17.0s P = 0.014 P = 0.042

    Precedence vs Brackets
  66. 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
  67. 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 }
  68. 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);
  69. Pure functions var score = 10; function doubleScore() { score

    = score * 2; } doubleScore(); var result = score; Impure
  70. var score = 10; function doubleScore(initialScore) { return initialScore *

    2; } var result = doubleScore(score); Pure functions Pure
  71. Impure vs Pure var score = 10; function doubleScore(initialScore) {

    return initialScore * 2; } var result = doubleScore(score); var score = 10; function doubleScore() { score = score * 2; } doubleScore(); var result = score;
  72. Inline vs Function function getAverage(values) { var sum = 0;

    for (var i = 0; i < values.length; i++) { sum += values[i]; } return sum / values.length; } result = getAverage([1, 2, 3]); function getSum(values) { var sum = 0; for (var i = 0; i < values.length; i++) { sum += values[i]; } return sum; } function getAverage(values) { return getSum(values) / values.length; } result = getAverage([1, 2, 3]);
  73. !a && !b === !(a || b) Boolean Algebra Expanded

    vs Simplified
  74. Publish full results https://howreadable.com Dec 2019

  75. Future

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

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

    • Increase participation: 1000+ • Analysis of existing code • Get help ... and funding.
  78. Takeaways • Descriptive > Prescriptive • Possible to objectively measure

    readability • Question arbitrary rules • If in doubt, try it out • Help us! info@howreadable.com
  79. 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