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 Slide

  2. Grammar

    View Slide

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

    View Slide

  4. Readable Code

    View Slide

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

    View Slide

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

    View Slide

  7. Grammar Readable Code

    View Slide

  8. .com

    View Slide

  9. Readable Code

    View Slide

  10. Writing code
    On your own
    For the computer
    Student

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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?

    View Slide

  15. Readability
    Structure
    Consistency
    Brevity
    Convention
    Syntax
    Naming
    Clarity
    Approach

    View Slide

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

    View Slide

  17. Grammar

    View Slide

  18. Grumpy English Teacher

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  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

    View Slide

  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

    View Slide

  26. ?
    Little green men Rachel and I

    View Slide

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

    View Slide

  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

    View Slide

  29. Readable Code?

    View Slide

  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

    View Slide

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


    View Slide

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

    View Slide

  33. Prescriptive Descriptive

    View Slide

  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

    View Slide

  35. Descriptive rules beneficial?

    View Slide

  36. Descriptive rules beneficial?

    View Slide

  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

    View Slide

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

    View Slide

  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

    View Slide

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

    View Slide

  41. View Slide

  42. View Slide

  43. View Slide

  44. View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  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

    View Slide

  51. Results

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

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

    View Slide

  58. array.filter(fn)
    Filtrate Residue

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

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

    View Slide

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

    View Slide

  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;

    View Slide

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

    View Slide

  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

    View Slide

  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
    }

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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;

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  75. Future

    View Slide

  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

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide