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

The Elements of Programming Style (HackConf 2019)

The Elements of Programming Style (HackConf 2019)

Bozhidar Batsov

October 13, 2019
Tweet

More Decks by Bozhidar Batsov

Other Decks in Programming

Transcript

  1. Привет!

    View full-size slide

  2. Божидар

    View full-size slide

  3. Why am I here?

    View full-size slide

  4. size=2
    start=0
    c=['Н', 'Н' ,'Н' ,'Н' ,'Н','Н','Н','Н','Н','Н','Н','Н','Н','Н']
    code_dictionary=Array.new()
    begin_size_code_dictionary=Array.new()
    end_string=String.new()
    code_dictionary=c.uniq.to_a
    decode_dictionary=c.uniq.to_a
    for i in 0...code_dictionary.size
    begin_size_code_dictionary[i]=i
    end
    c.size.times{
    if !code_dictionary.include?(c[start,size].to_s)#Comparation
    code_dictionary.push(c[start,size].to_s.chomp)
    start=start+(code_dictionary.last.size)/2-1
    size=2
    else
    size+=1;
    end
    }
    end_code=Array.new(code_dictionary.size)
    for i in begin_size_code_dictionary.size...code_dictionary.size
    end_code[i]=code_dictionary.index(code_dictionary[i].chop.chop)+1
    end_string+=code_dictionary[i].chop.chop
    end
    govnokod.ru

    View full-size slide

  5. The Elements
    of
    Style
    in
    Programming
    by Bozhidar Batsov

    View full-size slide

  6. Languages are hard

    View full-size slide

  7. Basic usage of a
    language is easy

    View full-size slide

  8. Айн-цу-цвайн-цу-дрън

    View full-size slide

  9. "Ту партс,
    съмтаймс люн,
    съмтаймс уин,
    соу,
    фърст дей релякс"

    View full-size slide

  10. The correct usage of
    a language is hard

    View full-size slide

  11. The effective usage of a
    language is very hard

    View full-size slide

  12. Българската политика
    е лайно в целофан.

    View full-size slide

  13. На малко прасе и нов
    началник никога не се
    радвам.

    View full-size slide

  14. Всичко хубаво в тая държава сме
    го направили ние, те не могат да го
    боядисат - от метрото до Северната
    дъга, Тракия, Марица, Струма…

    View full-size slide

  15. Живков и царя са ми като два
    университета. В една тема и двамата
    бяха много единни, че България и
    държавата са над всичко.

    View full-size slide

  16. Да мачкаш Цветанов е
    все едно с голо дупе
    таралеж да мачкаш.

    View full-size slide

  17. try 10 years

    View full-size slide

  18. http://norvig.com/21-days.html
    Teach Yourself
    Programming in Ten Years
    Peter Norvig

    View full-size slide

  19. Laziness is a virtue

    View full-size slide

  20. Use the active voice.

    View full-size slide

  21. My first visit to Pernik will always
    be remembered by me.
    lame

    View full-size slide

  22. I shall always remember my
    first visit to Pernik.
    legit

    View full-size slide

  23. The word personally
    is often unnecessary.

    View full-size slide

  24. Personally, I love Emacs.

    View full-size slide

  25. A Style Guide
    • a curated set of (supposedly) good practices
    • spares you the process of making trivial
    decisions
    • allows you to focus on the actual problems
    • simple and concise

    View full-size slide

  26. Style guides aren’t a
    replacement for
    thinking

    View full-size slide

  27. Programs must be
    written for people to
    read, and only
    incidentally for
    machines to execute.
    — Hal Abelson

    View full-size slide

  28. Similar rules apply to
    natural and
    programming languages

    View full-size slide

  29. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
    est laborum.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
    est laborum.
    Chapter I

    View full-size slide

  30. LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT, SED DO
    EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA. UT
    ENIM AD MINIM VENIAM, QUIS NOSTRUD EXERCITATION ULLAMCO LABORIS
    NISI UT ALIQUIP EX EA COMMODO CONSEQUAT. DUIS AUTE IRURE DOLOR
    IN REPREHENDERIT IN VOLUPTATE VELIT ESSE CILLUM DOLORE EU FUGIAT
    NULLA PARIATUR. EXCEPTEUR SINT OCCAECAT CUPIDATAT NON PROIDENT,
    SUNT IN CULPA QUI OFFICIA DESERUNT MOLLIT ANIM ID EST LABORUM.
    LOREM IPSUM DOLOR SIT AMET, CONSECTETUR
    ADIPISCING ELIT, SED DO EIUSMOD TEMPOR INCIDIDUNT UT
    LABORE ET DOLORE MAGNA ALIQUA. UT ENIM AD MINIM
    VENIAM, QUIS NOSTRUD EXERCITATION ULLAMCO LABORIS
    NISI UT ALIQUIP EX EA COMMODO CONSEQUAT. DUIS AUTE
    IRURE DOLOR IN REPREHENDERIT IN VOLUPTATE VELIT
    ESSE CILLUM DOLORE EU FUGIAT NULLA PARIATUR.
    EXCEPTEUR SINT OCCAECAT CUPIDATAT NON PROIDENT,
    SUNT IN CULPA QUI OFFICIA DESERUNT MOLLIT ANIM ID
    EST LABORUM.
    chapter i

    View full-size slide

  31. Български

    View full-size slide

  32. Правителство трябва да има на всяка цена, каза премиерът
    проф. Георги Близнашки пред журналисти в Котел, където беше
    по повод Деня на будителите. "Силно се надявам, че в
    следващите няколко дни, особено след като бъде връчен
    проучвателен мандат, разговорите ще придобият по-спокоен тон
    и ще се стигне до съставяне на правителство", заяви министър-
    председателят, цитиран от правителствената информационна
    служба.
    Той прогнозира тежки първи месеци за следващия кабинет,
    който трябва да предприеме неотложни и "не особено популярни
    мерки". Близнашки изрази надежда, че след това нещата ще
    тръгнат във възходяща линия, благодарение на финансовия
    ресурс, предвиден за страната ни по Споразумението за
    партньорство на ЕК с България до 2020 година.
    Глава 1

    View full-size slide

  33. ПРАВИТЕЛСТВО ТРЯБВА ДА ИМА НА ВСЯКА ЦЕНА, КАЗА
    ПРЕМИЕРЪТ ПРОФ. ГЕОРГИ БЛИЗНАШКИ ПРЕД ЖУРНАЛИСТИ В
    КОТЕЛ, КЪДЕТО БЕШЕ ПО ПОВОД ДЕНЯ НА БУДИТЕЛИТЕ.
    "СИЛНО СЕ НАДЯВАМ, ЧЕ В СЛЕДВАЩИТЕ НЯКОЛКО ДНИ,
    ОСОБЕНО СЛЕД КАТО БЪДЕ ВРЪЧЕН ПРОУЧВАТЕЛЕН МАНДАТ,
    РАЗГОВОРИТЕ ЩЕ ПРИДОБИЯТ ПО-СПОКОЕН ТОН И ЩЕ СЕ
    СТИГНЕ ДО СЪСТАВЯНЕ НА ПРАВИТЕЛСТВО", ЗАЯВИ
    МИНИСТЪР-ПРЕДСЕДАТЕЛЯТ, ЦИТИРАН ОТ ПРАВИТЕЛСТВЕНАТА
    ИНФОРМАЦИОННА СЛУЖБА.
    гЛаВа 1
    ТОЙ ПРОГНОЗИРА ТЕЖКИ ПЪРВИ МЕСЕЦИ ЗА СЛЕДВАЩИЯ
    КАБИНЕТ, КОЙТО ТРЯБВА ДА ПРЕДПРИЕМЕ НЕОТЛОЖНИ И "НЕ
    ОСОБЕНО ПОПУЛЯРНИ МЕРКИ". БЛИЗНАШКИ ИЗРАЗИ
    НАДЕЖДА, ЧЕ СЛЕД ТОВА НЕЩАТА ЩЕ ТРЪГНАТ ВЪВ
    ВЪЗХОДЯЩА ЛИНИЯ, БЛАГОДАРЕНИЕ НА ФИНАНСОВИЯ РЕСУРС,
    ПРЕДВИДЕН ЗА СТРАНАТА НИ ПО СПОРАЗУМЕНИЕТО ЗА
    ПАРТНЬОРСТВО НА ЕК С БЪЛГАРИЯ ДО 2020 ГОДИНА.

    View full-size slide

  34. def some_method
    do_something
    do_more
    do_more
    end

    View full-size slide

  35. def some_method
    do_something
    do_more
    do_more
    end

    View full-size slide

  36. sum = 1 + 2
    a, b = 1, 2
    [1, 2, 3].each { |e| puts e }
    class FooError < StandardError; end

    View full-size slide

  37. sum=1+2
    a,b=1,2
    [1,2,3].each{|e|puts e}
    class FooError

    View full-size slide

  38. Elementary Rules of
    Usage

    View full-size slide

  39. Form possessive
    singular of nouns by
    adding ’s.

    View full-size slide

  40. Bozhidar’s talk
    Batman’s batclaw
    Emacs’s magic

    View full-size slide

  41. Form predicate method
    names by adding “?”.

    View full-size slide

  42. even?
    completed?
    batman?

    View full-size slide

  43. Elementary Principles of
    Composition

    View full-size slide

  44. Make the paragraph
    the unit of composition.

    View full-size slide

  45. Make the method the
    unit of composition.

    View full-size slide

  46. Omit needless words.

    View full-size slide

  47. he is a man who

    View full-size slide

  48. Her story is a strange
    one.

    View full-size slide

  49. Omit needless words.

    View full-size slide

  50. if some_condition then
    # body omitted
    end

    View full-size slide

  51. def some_method
    # ...
    return result
    end

    View full-size slide

  52. Words and Expressions
    Commonly Misused

    View full-size slide

  53. farther
    further

    View full-size slide

  54. Do we have to go
    much farther?

    View full-size slide

  55. I decided to pursue
    the subject further.

    View full-size slide

  56. ==
    ===
    equal?
    eql?

    View full-size slide

  57. An Approach to Style

    View full-size slide

  58. Be consistent

    View full-size slide

  59. The user should update
    his config accordingly.
    They should also check…

    View full-size slide

  60. The user should update
    his config accordingly.
    They should also check…

    View full-size slide

  61. def something coll
    coll.collect(&:ala)
    end
    def something2(coll)
    coll.map { |x| x.bala }
    end

    View full-size slide

  62. Български

    View full-size slide

  63. Бързо мощно возило

    View full-size slide

  64. Коварен
    Терански
    Батълкруузър

    View full-size slide

  65. Активен борец против
    фашизма и капитализма

    View full-size slide

  66. $FIELD_SEPARATOR

    View full-size slide

  67. '%d %d' % [20, 10]

    View full-size slide

  68. sprintf('%d %d', 20, 10)

    View full-size slide

  69. sprintf(
    '%{first} %{second}',
    first: 20, second: 10
    )

    View full-size slide

  70. format('%{first} %{second}',
    first: 20, second: 10)

    View full-size slide

  71. Ruby
    is
    optimized
    for
    programmer
    happiness

    View full-size slide

  72. Ruby is a huge
    language

    View full-size slide

  73. Making the “right”
    decisions is hard

    View full-size slide

  74. puts "Hello, HackConf!"
    puts "Hello, HackConf!"
    puts "Hello, HackConf!”

    View full-size slide

  75. for i in 1..3
    puts "Hello, HackConf!”
    end

    View full-size slide

  76. 3.times do
    puts "Hello, HackConf!”
    end

    View full-size slide

  77. result = []
    names.each do |word|
    result << name.upcase
    end

    View full-size slide

  78. names.map { |name| name.upcase }

    View full-size slide

  79. names.map(&:upcase)

    View full-size slide

  80. names.map(_1.upcase)

    View full-size slide

  81. Are all those options
    even worth our while?

    View full-size slide

  82. 56 simple rules

    View full-size slide

  83. Format a program
    to help the reader
    understand it.

    View full-size slide

  84. Write clearly --
    don't be too clever.

    View full-size slide

  85. def user_signed_in?
    !!@current_user
    end
    def user_signed_in?
    !@current_user.nil?
    end

    View full-size slide

  86. Don't sacrifice
    clarity for small
    gains in efficiency.

    View full-size slide

  87. i = 1
    res = 0
    while i <= 10
    res += i
    i += 1
    end

    View full-size slide

  88. (1..10).reduce(:+)

    View full-size slide

  89. (N * (N + 1)) / 2

    View full-size slide

  90. (10 * (10 + 1)) / 2

    View full-size slide

  91. Don't diddle code to
    make it faster -- find a
    better algorithm.

    View full-size slide

  92. •Make it right before you make
    it faster.
    •Make it fail-safe before you
    make it faster.
    •Make it clear before you make
    it faster.

    View full-size slide

  93. Instrument your
    programs. Measure
    before making efficiency
    changes.

    View full-size slide

  94. Use variable names
    that mean something.

    View full-size slide

  95. age
    sex
    location

    View full-size slide

  96. age_over_18?

    View full-size slide

  97. Don’t repeat
    yourself.

    View full-size slide

  98. Parenthesize to
    avoid ambiguity.

    View full-size slide

  99. x || (y && z)

    View full-size slide

  100. Keep the code & its
    comments in sync.

    View full-size slide

  101. # This method does bla bla bla.
    # It returns an array of results.
    def bla_bla_bla
    res = Set.new
    # ...
    res
    end

    View full-size slide

  102. bla_bla_bla[0]
    # => Boom Boom Pow
    bla_bla_bla.uniq
    # => Kaboom!

    View full-size slide

  103. //private instance variable for storing age
    public static int age;

    View full-size slide

  104. //private instance variable for storing age
    public static int age;

    View full-size slide

  105. //private instance variable for storing age
    public static int age;

    View full-size slide

  106. Don’t repeat the code
    in the comments.

    View full-size slide

  107. # increment counter by 1
    counter += 1

    View full-size slide

  108. Don’t comment
    shitty code — fix it.

    View full-size slide

  109. //
    // Dear maintainer:
    //
    // Once you are done trying to 'optimize' this routine,
    // and have realized what a terrible mistake that was,
    // please increment the following counter as a warning
    // to the next guy:
    //
    // total_hours_wasted_here = 42
    //

    View full-size slide

  110. Fuck this
    shit!!!

    View full-size slide

  111. Style guides
    for
    programming languages

    View full-size slide

  112. PEP-8
    http://legacy.python.org/dev/peps/pep-0008/

    View full-size slide

  113. Sun Style Guide
    http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

    View full-size slide

  114. Google Style Guide
    https://google-styleguide.googlecode.com/svn/trunk/javaguide.html

    View full-size slide

  115. Effective Go
    https://golang.org/doc/effective_go.html

    View full-size slide

  116. StandardJS
    https://standardjs.com/

    View full-size slide

  117. PHP FIG Coding Style
    Guide
    http://www.php-fig.org/psr/psr-1/
    http://www.php-fig.org/psr/psr-2/

    View full-size slide

  118. Ruby Style Guide
    https://rubystyle.guide

    View full-size slide

  119. Clojure Style Guide
    https://guide.clojure.style

    View full-size slide

  120. Languages are
    always evolving

    View full-size slide

  121. Good style practices
    are evolving as well

    View full-size slide

  122. { :batman => 'Bruce',
    :superman => 'Clark',
    :zorro => 'Diego',
    :catwoman => 'Selina' }

    View full-size slide

  123. { batman: 'Bruce',
    superman: 'Clark',
    zorro: 'Diego',
    catwoman: 'Selina' }

    View full-size slide

  124. Style consistency is of
    paramount importance

    View full-size slide

  125. Community
    Personal Project
    Company

    View full-size slide

  126. Community
    Project
    Company

    View full-size slide

  127. Style separates
    the good from
    the great

    View full-size slide

  128. One more thing…

    View full-size slide