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. Daniel van Berzon
    @ocastahq ocasta.com
    @dvberzon vanberzon.com
    Readable code
    (Available without prescription)

    View full-size slide

  2. “Rachel and me went
    to the cinema”
    “Rachel and I went
    to the cinema”
    A B
    C

    View full-size slide

  3. Readable Code

    View full-size slide

  4. A
    B
    C
    const sorted = input
    .split('')
    .sort()
    .join('');
    const chars = input.split('');
    const sortedChars = chars.sort();
    const sorted = sortedChars.join('')

    View full-size slide

  5. Grammar Readable Code
    Spanish
    Dutch
    Politics
    Photography Magic Singing
    Guilbert & Sullivan
    FC Barcelona Cheese
    Flamenco
    Film
    Popular Science

    View full-size slide

  6. Grammar Readable Code

    View full-size slide

  7. Readable Code

    View full-size slide

  8. Writing code
    On your own
    For the computer
    Student

    View full-size slide

  9. Reading code
    Collaborating
    For developers
    Professional
    Reading : Writing
    10 : 1
    - Robert C Martin

    View full-size slide

  10. Student Professional
    Cool
    Clever
    Efficient
    Succinct
    Exciting
    Clear
    Simple
    Intuitive
    Structured
    Boring
    write_code => => read_code

    View full-size slide

  11. const = 0;
    • Too many options
    • Spoilers
    • Other people
    … is hard to write
    Code that is easy to read
    z

    View full-size slide

  12. 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?

    View full-size slide

  13. Readability
    Structure
    Consistency
    Brevity
    Convention
    Syntax
    Naming
    Clarity
    Approach

    View full-size slide

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

    View full-size slide

  15. Grumpy English Teacher

    View full-size slide

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

    View full-size slide

  17. What is he on about?
    preposition
    About what is he on?
    On about what is he? !

    View full-size slide

  18. “Rachel and me went
    to the cinema”
    “Rachel and I went
    to the cinema”
    A B
    C

    View full-size slide

  19. 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. !!

    View full-size slide

  20. 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

    View full-size slide

  21. 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

    View full-size slide

  22. 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

    View full-size slide

  23. ?
    Little green men Rachel and I

    View full-size slide

  24. Noam Chomsky
    Universal Grammar
    Humans are born with an
    innate understanding of
    grammar.
    Prescriptive grammar
    Descriptive grammar

    View full-size slide

  25. 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

    View full-size slide

  26. Readable Code?

    View full-size slide

  27. 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

    View full-size slide

  28. // 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 ...


    View full-size slide

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

    View full-size slide

  30. Prescriptive Descriptive

    View full-size slide

  31. No native speakers of:
    JavaScript
    Python
    C / C++
    Ruby
    Java
    Universal grammar applies to native language speakers
    Flaw in the metaphor
    Baṣa Jawa

    View full-size slide

  32. Descriptive rules beneficial?

    View full-size slide

  33. Descriptive rules beneficial?

    View full-size slide

  34. 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

    View full-size slide

  35. Niall Coleman Clarke - Daniel van Berzon - Jake 'Sid' Smith

    View full-size slide

  36. 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

    View full-size slide

  37. Metric for readability?
    Can a developer predict
    output of code?
    Time it takes them to
    understand the code

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  40. Chaining
    75%
    50%
    }
    }
    a.b.c
    x = a.b
    x.c
    Methodology

    View full-size slide

  41. 11 Experiments
    Each testing a different
    coding construct
    6 Exercises
    chaining methods

    View full-size slide

  42. 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

    View full-size slide

  43. 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

    View full-size slide

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

    View full-size slide

  45. Chi-Squared test
    Students T-test
    P value P < 0.05
    Chaining vs Intermediate

    View full-size slide

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

    View full-size slide

  47. P = 0.044
    P = 0.001
    Chaining vs Intermediate
    89.2% 93.8%
    30.5s 39.3s

    View full-size slide

  48. 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

    View full-size slide

  49. Naming
    There are only two hard things in Computer Science:
    cache invalidation and naming things.
    - Phil Karlton

    View full-size slide

  50. array.filter(fn)
    Filtrate Residue

    View full-size slide

  51. 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');

    View full-size slide

  52. Generic vs Specific
    naming
    95.3% 97.6%
    18.7s 19.9s
    P = 0.045
    P = 0.125

    View full-size slide

  53. 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

    View full-size slide

  54. Constructs:
    Chaining methods
    Operator precedence
    Pure functions
    Abstraction
    Boolean algebra
    If statements
    Naming
    Ternary operators
    Inline functions
    Early return
    Comments

    View full-size slide

  55. 8/2*(2+2)
    (8/2)*(2+2)
    =16
    8/(2*(2+2))
    =1
    Operator precedence
    Operator precedence

    View full-size slide

  56. 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;

    View full-size slide

  57. 91.7% 97.2%
    19.1s 17.0s
    P = 0.014
    P = 0.042
    Precedence vs Brackets

    View full-size slide

  58. 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

    View full-size slide

  59. 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
    }

    View full-size slide

  60. 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);

    View full-size slide

  61. Pure functions
    var score = 10;
    function doubleScore() {
    score = score * 2;
    }
    doubleScore();
    var result = score;
    Impure

    View full-size slide

  62. var score = 10;
    function doubleScore(initialScore) {
    return initialScore * 2;
    }
    var result = doubleScore(score);
    Pure functions
    Pure

    View full-size slide

  63. 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;

    View full-size slide

  64. 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]);

    View full-size slide

  65. !a && !b === !(a || b)
    Boolean Algebra
    Expanded vs Simplified

    View full-size slide

  66. Publish full results
    https://howreadable.com
    Dec 2019

    View full-size slide

  67. 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

    View full-size slide

  68. Improvements
    • Explore different methodologies
    - Ask developers change code
    • Increase participation: 1000+
    • Analysis of existing code
    • Get help ... and funding.

    View full-size slide

  69. Takeaways
    • Descriptive > Prescriptive
    • Possible to objectively measure readability
    • Question arbitrary rules
    • If in doubt, try it out
    • Help us!
    [email protected]

    View full-size slide

  70. 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

    View full-size slide