Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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

Daniel van Berzon

November 22, 2019
Tweet

More Decks by Daniel van Berzon

Other Decks in Technology

Transcript

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

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

    & Sullivan FC Barcelona Cheese Flamenco Film Popular Science
  3. const = 0; • Too many options • Spoilers •

    Other people … is hard to write Code that is easy to read z
  4. 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?
  5. 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. !!
  6. 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
  7. 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
  8. 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
  9. Noam Chomsky Universal Grammar Humans are born with an innate

    understanding of grammar. Prescriptive grammar Descriptive grammar
  10. 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
  11. 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
  12. // 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 ... “ ”
  13. No native speakers of: JavaScript Python C / C++ Ruby

    Java Universal grammar applies to native language speakers Flaw in the metaphor Baṣa Jawa
  14. 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
  15. 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
  16. Metric for readability? Can a developer predict output of code?

    Time it takes them to understand the code
  17. 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
  18. 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
  19. 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
  20. Naming There are only two hard things in Computer Science:

    cache invalidation and naming things. - Phil Karlton
  21. 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');
  22. 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
  23. Constructs: Chaining methods Operator precedence Pure functions Abstraction Boolean algebra

    If statements Naming Ternary operators Inline functions Early return Comments
  24. 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;
  25. 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
  26. 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 }
  27. 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);
  28. Pure functions var score = 10; function doubleScore() { score

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

    2; } var result = doubleScore(score); Pure functions Pure
  30. 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;
  31. 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]);
  32. 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
  33. Improvements • Explore different methodologies - Ask developers change code

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

    readability • Question arbitrary rules • If in doubt, try it out • Help us! [email protected]
  35. 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