The Elements of Style in Programming (HWSW Mobile! 2016)

The Elements of Style in Programming (HWSW Mobile! 2016)

Slide deck from my presentation at HWSW Mobile! 2016 in Budapest.

1be785d1d788b82929e55fc83a9f0aaa?s=128

Bozhidar Batsov

November 23, 2016
Tweet

Transcript

  1. The Elements of Style in Programming by Bozhidar Batsov

  2. Szervusz!

  3. None
  4. Божидар

  5. Bozhidar

  6. Bozho cool

  7. Bozo not cool

  8. Bug cool

  9. None
  10. Magical Sofia City Sofia, Bulgaria

  11. Sofia, Bulgaria

  12. None
  13. I’m an Emacs fanatic

  14. bbatsov

  15. None
  16. Our beloved leader/CTO

  17. None
  18. None
  19. None
  20. None
  21. None
  22. Why am I here?

  23. None
  24. 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
  25. Languages are hard

  26. None
  27. None
  28. None
  29. Basic usage of a language is easy

  30. “Two parts, sometimes lyun, sometimes win, so, first day relyax…”

  31. I need an interpreter!

  32. “You are the BIGGEST!”

  33. The correct usage of a language is hard

  34. The effective usage of a language is very hard

  35. not really

  36. try 10 years

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

  38. None
  39. None
  40. None
  41. Use the active voice.

  42. My first visit to Budapest will always be remembered by

    me. lame
  43. I shall always remember my first visit to Budapest. legit

  44. The word personally is often unnecessary.

  45. Personally, I love Emacs.

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

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

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

  50. None
  51. English

  52. 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
  53. 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
  54. Magyar

  55. None
  56. None
  57. A Fideszt démonizálók közül meglepően sokan képzelik úgy, hogy a

    kor mánypár t valami nindzsahadsereghez hasonló, tökéletesen kiképzett, arctalan, fegyelmezett katonákból álló sereg, egyfajta f é l e l m e t e s e n h a t é k o n y p o l i t i k a i - é s propagandagépezet. Ugyanezt képzeli ráadásul, nem kis büszkeséggel, egy rakás Fidesz-rajongó is. Egy jó propagandaminiszter viszont tudja, hogy ez az imidzs egy határig kedvező ugyan a pártnak, de ha túlzottan kizárólagossá válik, a választók már nem tudnak azonosulni vele és a túlhajtott profizásnak meg klónhadseregezésnek elhidegülés lesz a vége. Fejezet 1
  58. A FIDESZT DéMONIZáLóK KöZüL MEGLEPőEN SOKAN KéPZELIK úGY, HOGY A

    KORMáNYPáRT VALAMI NINDZSAHADSEREGHEZ HASONLó, T ö K é L E T E S E N K I K é P Z E T T, A R C TA L A N , FEGYELMEZETT KATONáKBóL áLLó SEREG, EGYFAJTA FéLELMETESEN HATéKONY POLITIKAI- éS PROPAGANDAGéPEZET. FeJeZet 1 U G YA N E Z T K é P Z E L I R á A D á S U L , N E M K I S BüSZKESéGGEL, EGY RAKáS FIDESZ-RAJONGó IS. EGY Jó PROPAGANDAMINISZTER VISZONT TUDJA, HOGY EZ AZ IMIDZS EGY HATáRIG KEDVEZő UGYAN A PáRTNAK, DE HA TúLZOTTAN KIZáRóLAGOSSá VáLIK, A VáLASZTóK MáR NEM TUDNAK AZONOSULNI VELE éS A T ú L H A J T O T T P R O F I Z á S N A K M E G KLóNHADSEREGEZéSNEK ELHIDEGüLéS LESZ A VéGE.
  59. Ruby

  60. def some_method do_something do_more do_more end

  61. def some_method do_something do_more do_more end

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

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

    [1, 2, 3].each { |e| puts e } class FooError < StandardError; end
  64. English

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

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

  67. Ruby

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

  69. even? completed? batman?

  70. English

  71. Make the paragraph the unit of composition.

  72. Ruby

  73. Make the method the unit of composition.

  74. English

  75. Omit needless words.

  76. he is a man who

  77. Her story is a strange one.

  78. Ruby

  79. Omit needless words.

  80. if some_condition then # body omitted end

  81. def some_method # ... return result end

  82. English

  83. farther further

  84. Do we have to go much farther?

  85. I decided to pursue the subject further.

  86. Ruby

  87. == === equal? eql?

  88. An approach to style

  89. Be consistent

  90. English

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

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

    check…
  93. Ruby

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

    x.bala } end
  95. Be clear

  96. Magyar

  97. MÁV

  98. Megint Állunk Vazze

  99. BKV

  100. Biztos Késünk Vazze

  101. FIDESZ

  102. Forintot Ide De SZaporán

  103. Ruby

  104. $:

  105. $LOAD_PATH

  106. $;

  107. $FIELD_SEPARATOR

  108. $*

  109. $ARGV

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

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

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

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

  114. Ruby is optimized for programmer happiness

  115. Ruby is a huge language

  116. Making the “right” decisions is hard

  117. None
  118. puts "Hello, Budapest!" puts "Hello, Budapest!" puts "Hello, Budapest!"

  119. for i in 1..3 puts "Hello, Budapest!" end

  120. 3.times do puts "Hello, Budapest!" end

  121. 3.times do puts %(Hello, Budapest!) end

  122. 3.times do puts %Q(Hello, Budapest!) end

  123. 3.times do puts 'Hello, Budapest!' end

  124. 3.times do puts %q(Hello, Budapest!) end

  125. None
  126. None
  127. Are all those options worth our while?

  128. None
  129. None
  130. None
  131. None
  132. 56 simple rules

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

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

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

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

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

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

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

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

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

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

  144. Use variable names that mean something.

  145. a s l

  146. age sex location

  147. age_over_18?

  148. adult?

  149. Don’t repeat yourself.

  150. Parenthesize to avoid ambiguity.

  151. x || y && z

  152. x || (y && z)

  153. Keep the code & its comments in sync.

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

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

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

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

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

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

  160. # increment counter by 1 counter += 1

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

  162. // // 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 //
  163. Fuck this shit!!!

  164. Style guides for programming languages

  165. Python

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

  167. Java

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

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

  170. Go

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

  172. gofmt

  173. None
  174. Airbnb Style Guide https://github.com/airbnb/javascript

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

  176. PHP

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

  178. None
  179. Ruby Style Guide https://github.com/bbatsov/ruby-style-guide

  180. Clojure

  181. Clojure Style Guide https://github.com/bbatsov/clojure-style-guide

  182. Swift

  183. Swift

  184. Swift Style Guide https://github.com/raywenderlich/swift-style-guide

  185. Languages are always evolving

  186. Good style practices are evolving as well

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

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

  189. Style consistency is of paramount importance

  190. Community PersonalProject Company

  191. Community Project Company

  192. Style separates the good from the great!

  193. Felina

  194. Epilogue twitter: @bbatsov github: @bbatsov http//batsov.com http://emacsredux.com HWSW Mobile! Budapest,

    Hungary 23.11.2016