Save 37% off PRO during our Black Friday Sale! »

The Elements of Style in Programming (WebCamp Zagreb 2015)

The Elements of Style in Programming (WebCamp Zagreb 2015)

Slide deck from my talk at WebCamp Zagreb 2015.

Efd2550fb5f3059d815e731ecd61b701?s=128

Bozhidar Batsov

March 23, 2016
Tweet

Transcript

  1. The Elements of Style in Programming by Bozhidar Batsov

  2. Dobar dan Zagrebe!

  3. Божидар

  4. Božidar

  5. None
  6. None
  7. I’m an Emacs fanatic

  8. bbatsov

  9. None
  10. Sasha, our beloved leader/CTO

  11. None
  12. @bbatsov

  13. None
  14. Why am I here?

  15. None
  16. 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
  17. Languages are hard

  18. None
  19. Basic usage of a language is easy

  20. Pipl mast trast as

  21. "I was day after 
 yesterday
 in Hungary"

  22. The correct usage of a language is hard

  23. The effective usage of a language is very hard

  24. not really

  25. try 10 years

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

  27. None
  28. None
  29. None
  30. Use the active voice.

  31. My first visit to Zagreb will always be remembered by

    me. lame
  32. I shall always remember my first visit to Zagreb. legit

  33. The word personally is often unnecessary.

  34. Personally, I love Emacs.

  35. 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
  36. Style guides aren’t a replacement for thinking

  37. Programs must be written for people to read, and only

    incidentally for machines to execute. — Hal Abelson
  38. Similar rules apply to natural and programming languages

  39. None
  40. English

  41. 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
  42. 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
  43. Hrvatski

  44. Trebaju nam promjene prema otkrivanju i održavanju perspektive razvoja i

    napretka. Naša koalicija najavljuje promjene – promjene koje će oživjeti gospodarstvo kao podlogu razvitka, koje će teret reformi ravnomjernije podijeliti između bogatih i siromašnih, koje će omogućiti odgovornu, funkcionalnu i poštenu upravu, koje će racionalizirati potrošnju i javni rashod, a osigurati standard građana, koje će uvesti pravo zajednice na dio dobiti koju pojedinci izvlače ekstraprofitom, pretvarajući tuđi rad u svoju imovinu. 
 Mi najavljujemo promjenu prirode hrvatskoga kapitalizma i konačni odmak od prakse kapitalizma perifernoga, nekontroliranog, pa i nezakonitog profita, bogaćenja na štetu nacionalnih interesa i podcjenjivanja i odbacivanja prava rada i radnika. Naše promjene ne vode prema slabljenju države, nego prema jačanju uloge odgovorne države, a istodobno jačanju uloge njezinih građana. Poglavlje 1
  45. TREBAJU NAM PROMJENE PREMA OTKRIVANJU I ODRŽAVANJU PERSPEKTIVE RAZVOJA I

    NAPRETKA. NAŠA KOALICIJA NAJAVLJUJE PROMJENE – PROMJENE KOJE ĆE OŽIVJETI GOSPODARSTVO KAO PODLOGU RAZVITKA, KOJE ĆE TERET REFORMI RAVNOMJERNIJE PODIJELITI IZMEĐU BOGATIH I SIROMAŠNIH, KOJE ĆE OMOGUĆITI ODGOVORNU, FUNKCIONALNU I POŠTENU UPRAVU, KOJE ĆE RACIONALIZIRATI POTROŠNJU I JAVNI RASHOD, A OSIGURATI STANDARD GRAĐANA, KOJE ĆE UVESTI PRAVO ZAJEDNICE NA DIO DOBITI KOJU POJEDINCI IZVLAČE EKSTRAPROFITOM, PRETVARAJUĆI TUĐI RAD U SVOJU IMOVINU. pOgLaVljE 1 MI NAJAVLJUJEMO PROMJENU PRIRODE HRVATSKOGA KAPITALIZMA I KONAČNI ODMAK OD PRAKSE KAPITALIZMA PERIFERNOGA, NEKONTROLIRANOG, PA I NEZAKONITOG PROFITA, B O G A Ć E N J A N A Š T E T U N A C I O N A L N I H I N T E R E S A I PODCJENJIVANJA I ODBACIVANJA PRAVA RADA I RADNIKA. SADAŠNJA VLAST SAMO JE ZAŠTITNIK I JAMAC NASTAVKA TAKVE PRAKSE. NAŠE PROMJENE NE VODE PREMA SLABLJENJU DRŽAVE, NEGO PREMA JAČANJU ULOGE ODGOVORNE DRŽAVE
  46. Ruby

  47. def some_method do_something do_more do_more end

  48. def some_method do_something do_more do_more end

  49. sum = 1 + 2 a, b = 1, 2

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

  51. English

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

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

  54. Ruby

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

  56. even? completed? batman?

  57. English

  58. Make the paragraph the unit of composition.

  59. Ruby

  60. Make the method the unit of composition.

  61. English

  62. Omit needless words.

  63. he is a man who

  64. Her story is a strange one.

  65. Ruby

  66. Omit needless words.

  67. if some_condition then # body omitted end

  68. def some_method # ... return result end

  69. English

  70. farther further

  71. Do we have to go much farther?

  72. I decided to pursue the subject further.

  73. Ruby

  74. == === equal? eql?

  75. An approach to style

  76. Be consistent

  77. English

  78. The user should update his config accordingly. They should also

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

    check…
  80. Ruby

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

    x.bala } end
  82. Be clear

  83. Hrvatski

  84. HP

  85. Hladno Pivo

  86. DNK

  87. Da Nije Komšijin

  88. USKOK

  89. Ured za suzbijanje korupcije i organiziranog kriminaliteta

  90. Ruby

  91. $:

  92. $LOAD_PATH

  93. $;

  94. $FIELD_SEPARATOR

  95. $*

  96. $ARGV

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

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

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

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

  101. Ruby is optimized for programmer happiness

  102. Ruby is a huge language

  103. Making the “right” decisions is hard

  104. puts "Hello, WebCamp!" puts "Hello, WebCamp!" puts "Hello, WebCamp!"

  105. for i in 1..3 puts "Hello, WebCamp!" end

  106. 3.times do puts "Hello, WebCamp!" end

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

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

  109. names.map(&:upcase)

  110. None
  111. None
  112. None
  113. 56 simple rules

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

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

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

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

  118. i = 1 res = 0 while i <= 10

    res += i i += 1 end
  119. (1..10).reduce(:+)

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

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

  122. Don't diddle code to make it faster -- find a

    better algorithm.
  123. •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.
  124. Instrument your programs. Measure before making efficiency changes.

  125. Use variable names that mean something.

  126. a s l

  127. age sex location

  128. age_over_18?

  129. adult?

  130. Don’t repeat yourself.

  131. Parenthesize to avoid ambiguity.

  132. x || y && z

  133. x || (y && z)

  134. Keep the code & its comments in sync.

  135. # This method does bla bla bla. # It returns

    an array of results. def bla_bla_bla res = Set.new # ... res end
  136. bla_bla_bla[0] # => Boom Boom Pow bla_bla_bla.uniq # => Kaboom!

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

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

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

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

  141. # increment counter by 1 counter += 1

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

  143. // // 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 //
  144. Fuck this shit!!!

  145. Style guides for programming languages

  146. Python

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

  148. Java

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

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

  151. Go

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

  153. gofmt

  154. None
  155. Airbnb Style Guide https://github.com/airbnb/javascript

  156. Google Style Guide https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

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

  159. None
  160. Ruby Style Guide https://github.com/bbatsov/ruby-style-guide

  161. None
  162. Clojure Style Guide https://github.com/bbatsov/clojure-style-guide

  163. Languages are always evolving

  164. Good style practices are evolving as well

  165. { :batman => 'Bruce', :superman => 'Clark', :zorro => 'Diego',

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

  167. Style consistency is of paramount importance

  168. Community Personal Project Company

  169. Community Project Company

  170. Style separates the good from the great

  171. Felina

  172. One more thing…

  173. None