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 Slide

  2. Привет!

    View Slide

  3. View Slide

  4. View Slide

  5. Божидар

    View Slide

  6. @bbatsov

    View Slide

  7. View Slide

  8. View Slide

  9. Why am I here?

    View Slide

  10. View Slide

  11. View Slide

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

  13. The Elements
    of
    Style
    in
    Programming
    by Bozhidar Batsov

    View Slide

  14. Languages are hard

    View Slide

  15. View Slide

  16. Basic usage of a
    language is easy

    View Slide

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

    View Slide

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

    View Slide

  19. The correct usage of
    a language is hard

    View Slide

  20. The effective usage of a
    language is very hard

    View Slide

  21. View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  27. not really

    View Slide

  28. try 10 years

    View Slide

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

    View Slide

  30. View Slide

  31. Laziness is a virtue

    View Slide

  32. View Slide

  33. Use the active voice.

    View Slide

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

    View Slide

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

    View Slide

  36. The word personally
    is often unnecessary.

    View Slide

  37. Personally, I love Emacs.

    View Slide

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

  39. Style guides aren’t a
    replacement for
    thinking

    View Slide

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

    View Slide

  41. Similar rules apply to
    natural and
    programming languages

    View Slide

  42. View Slide

  43. English

    View Slide

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

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

  46. Български

    View Slide

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

    View Slide

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

    View Slide

  49. Ruby

    View Slide

  50. def some_method
    do_something
    do_more
    do_more
    end

    View Slide

  51. def some_method
    do_something
    do_more
    do_more
    end

    View Slide

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

    View Slide

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

    View Slide

  54. Elementary Rules of
    Usage

    View Slide

  55. English

    View Slide

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

    View Slide

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

    View Slide

  58. Ruby

    View Slide

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

    View Slide

  60. even?
    completed?
    batman?

    View Slide

  61. View Slide

  62. Elementary Principles of
    Composition

    View Slide

  63. English

    View Slide

  64. Make the paragraph
    the unit of composition.

    View Slide

  65. Ruby

    View Slide

  66. Make the method the
    unit of composition.

    View Slide

  67. English

    View Slide

  68. Omit needless words.

    View Slide

  69. he is a man who

    View Slide

  70. Her story is a strange
    one.

    View Slide

  71. Ruby

    View Slide

  72. Omit needless words.

    View Slide

  73. if some_condition then
    # body omitted
    end

    View Slide

  74. def some_method
    # ...
    return result
    end

    View Slide

  75. View Slide

  76. Words and Expressions
    Commonly Misused

    View Slide

  77. English

    View Slide

  78. farther
    further

    View Slide

  79. Do we have to go
    much farther?

    View Slide

  80. I decided to pursue
    the subject further.

    View Slide

  81. Ruby

    View Slide

  82. ==
    ===
    equal?
    eql?

    View Slide

  83. View Slide

  84. An Approach to Style

    View Slide

  85. Be consistent

    View Slide

  86. English

    View Slide

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

    View Slide

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

    View Slide

  89. Ruby

    View Slide

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

    View Slide

  91. Be clear

    View Slide

  92. Български

    View Slide

  93. БМВ

    View Slide

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

    View Slide

  95. КТБ

    View Slide

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

    View Slide

  97. АБПФК

    View Slide

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

    View Slide

  99. Ruby

    View Slide

  100. $:

    View Slide

  101. $LOAD_PATH

    View Slide

  102. $;

    View Slide

  103. $FIELD_SEPARATOR

    View Slide

  104. $*

    View Slide

  105. $ARGV

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  110. Ruby
    is
    optimized
    for
    programmer
    happiness

    View Slide

  111. Ruby is a huge
    language

    View Slide

  112. Making the “right”
    decisions is hard

    View Slide

  113. View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  119. names.map(&:upcase)

    View Slide

  120. names.map(_1.upcase)

    View Slide

  121. View Slide

  122. View Slide

  123. Are all those options
    even worth our while?

    View Slide

  124. View Slide

  125. View Slide

  126. View Slide

  127. 56 simple rules

    View Slide

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

    View Slide

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

    View Slide

  130. def user_signed_in?
    [email protected]_user
    end
    def user_signed_in?
    [email protected]_user.nil?
    end

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  137. •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 Slide

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

    View Slide

  139. Use variable names
    that mean something.

    View Slide

  140. a
    s
    l

    View Slide

  141. age
    sex
    location

    View Slide

  142. age_over_18?

    View Slide

  143. adult?

    View Slide

  144. Don’t repeat
    yourself.

    View Slide

  145. Parenthesize to
    avoid ambiguity.

    View Slide

  146. x || y && z

    View Slide

  147. x || (y && z)

    View Slide

  148. Keep the code & its
    comments in sync.

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  154. View Slide

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

    View Slide

  156. # increment counter by 1
    counter += 1

    View Slide

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

    View Slide

  158. //
    // 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 Slide

  159. Fuck this
    shit!!!

    View Slide

  160. View Slide

  161. Style guides
    for
    programming languages

    View Slide

  162. Python

    View Slide

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

    View Slide

  164. Java

    View Slide

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

    View Slide

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

    View Slide

  167. Go

    View Slide

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

    View Slide

  169. gofmt

    View Slide

  170. View Slide

  171. StandardJS
    https://standardjs.com/

    View Slide

  172. View Slide

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

    View Slide

  174. View Slide

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

    View Slide

  176. View Slide

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

    View Slide

  178. Languages are
    always evolving

    View Slide

  179. Good style practices
    are evolving as well

    View Slide

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

    View Slide

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

    View Slide

  182. Style consistency is of
    paramount importance

    View Slide

  183. Community
    Personal Project
    Company

    View Slide

  184. Community
    Project
    Company

    View Slide

  185. Style separates
    the good from
    the great

    View Slide

  186. Felina

    View Slide

  187. One more thing…

    View Slide

  188. View Slide