Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 256 lines (202 sloc) 8.776 kB
dc31232 initial version
Bozhidar Batsov authored
1 # Abstract
2
3 This document was created when I as the Technical Lead of the company
4 in which I work for was asked by the CTO to create some internal
5 documents describing good style and best practices for Ruby
6 programming. I started off by copying
7 [this existing style guide](https://github.com/chneukirchen/styleguide),
8 since I concurred with most of the points in it and started to built
9 upon it. I hope it will be useful to other people as well and I hope
10 that I'll get a lot of feedback and suggestions on how to improve the
11 guide for the benefit of the entire Ruby community.
12
13 ## Formatting
14
15 * Use UTF-8 as the source file encoding.
16 * Use 2 space indent, no tabs. (Your editor/IDE should have a setting to help you with that)
17 * Use Unix-style line endings. (Linux/OSX users are covered by default, Windows users have to be extra careful)
18 * if you're using Git you might want to do this `$ git config --global core.autocrlf true` to protect your project from Windows line endings creeping into your project
19 * Use spaces around operators, after commas, colons and semicolons, around { and before }.
20
376cc0a fixed indentation
Bozhidar Batsov authored
21 sum = 1 + 2
22 a, b = 1, 2
23 1 > 2 ? true : false; puts "Hi"
24 [1, 2, 3].each { |e| puts e }
dc31232 initial version
Bozhidar Batsov authored
25
26 * No spaces after (, [ and before ], ).
27
9259e8c more indentation fixes
Bozhidar Batsov authored
28 some(arg).other
29 [1, 2, 3].length
dc31232 initial version
Bozhidar Batsov authored
30
be05f8d minor fix
Bozhidar Batsov authored
31 * Indent **when** as deep as **case**. (as suggested in the Pickaxe)
dc31232 initial version
Bozhidar Batsov authored
32
9259e8c more indentation fixes
Bozhidar Batsov authored
33 case
34 when song.name == "Misty"
35 puts "Not again!" when song.duration > 120
36 puts "Too long!" when Time.now.hour > 21
37 puts "It's too late"
38 else
39 song.play
40 end
dc31232 initial version
Bozhidar Batsov authored
41
9259e8c more indentation fixes
Bozhidar Batsov authored
42 kind = case year
be05f8d minor fix
Bozhidar Batsov authored
43 when 1850..1889 then "Blues"
44 when 1890..1909 then "Ragtime"
45 when 1910..1929 then "New Orleans Jazz" when 1930..1939 then "Swing"
46 when 1940..1950 then "Bebop"
47 else "Jazz"
48 end
dc31232 initial version
Bozhidar Batsov authored
49
50 * Use an empty line before the return value of a method (unless it
51 only has one line), and an empty line between defs.
52
9259e8c more indentation fixes
Bozhidar Batsov authored
53 def some_method
54 do_something
55 do_something_else
dc31232 initial version
Bozhidar Batsov authored
56
9259e8c more indentation fixes
Bozhidar Batsov authored
57 result
58 end
dc31232 initial version
Bozhidar Batsov authored
59
9259e8c more indentation fixes
Bozhidar Batsov authored
60 def some_method
61 result
62 end
dc31232 initial version
Bozhidar Batsov authored
63 * Use RDoc and its conventions for API documentation. Don't put an
64 empty line between the comment block and the **def**.
65 * Use empty lines to break up a method into logical paragraphs.
66 * Keep lines fewer than 80 characters.
67 * Emacs users should really have a look at whitespace-mode
68 * Avoid trailing whitespace.
69 * Emacs users - whitespace-mode again comes to the rescue
70
71 ## Syntax
72
73 * Use **def** with parentheses when there are arguments. Omit the parentheses when the method doesn't accept any arguments.
9259e8c more indentation fixes
Bozhidar Batsov authored
74 def some_method
75 # body omitted
76 end
dc31232 initial version
Bozhidar Batsov authored
77
9259e8c more indentation fixes
Bozhidar Batsov authored
78 def some_method_with_arguments(arg1, arg2)
79 # body omitted
80 end
dc31232 initial version
Bozhidar Batsov authored
81
82 * Never use **for**, unless you exactly know why. Most of the time iterators should be used instead.
9259e8c more indentation fixes
Bozhidar Batsov authored
83 arr = [1, 2, 3]
dc31232 initial version
Bozhidar Batsov authored
84
9259e8c more indentation fixes
Bozhidar Batsov authored
85 # bad
86 for elem in arr do
87 puts elem
88 end
dc31232 initial version
Bozhidar Batsov authored
89
9259e8c more indentation fixes
Bozhidar Batsov authored
90 # good
91 arr.each { |elem| puts elem }
dc31232 initial version
Bozhidar Batsov authored
92 * Never use **then** for multiline **if/unless**.
93
9259e8c more indentation fixes
Bozhidar Batsov authored
94 # bad
95 if x.odd? then
96 puts "odd"
97 end
dc31232 initial version
Bozhidar Batsov authored
98
9259e8c more indentation fixes
Bozhidar Batsov authored
99 # good
100 if x.odd?
101 puts "odd"
102 end
dc31232 initial version
Bozhidar Batsov authored
103
104 * Use **when x; ...** for one-line cases.
105 * Use &&/|| for boolean expressions, and/or for control flow. (Rule
106 of thumb: If you have to use outer parentheses, you are using the
107 wrong operators.)
108 * Avoid multiline ?: (the ternary operator), use **if/unless** instead.
109 * Favor modifier **if/unless** usage when you have a single-line body.
9259e8c more indentation fixes
Bozhidar Batsov authored
110 # bad
111 if some_condition
112 do_something
113 end
dc31232 initial version
Bozhidar Batsov authored
114
9259e8c more indentation fixes
Bozhidar Batsov authored
115 # good
116 do_something if some_condition
dc31232 initial version
Bozhidar Batsov authored
117
9259e8c more indentation fixes
Bozhidar Batsov authored
118 # another good option
119 some_condition && do_something
dc31232 initial version
Bozhidar Batsov authored
120
121 * Favor **unless** over **if** for negative conditions:
9259e8c more indentation fixes
Bozhidar Batsov authored
122 # bad
123 do_something if !some_condition
dc31232 initial version
Bozhidar Batsov authored
124
9259e8c more indentation fixes
Bozhidar Batsov authored
125 # good
126 do_something unless some_condition
dc31232 initial version
Bozhidar Batsov authored
127
9259e8c more indentation fixes
Bozhidar Batsov authored
128 # another good option
129 some_condition || do_something
dc31232 initial version
Bozhidar Batsov authored
130 * Suppress superfluous parentheses when calling methods, but keep them
131 when calling "functions", i.e. when you use the return value in the
132 same line.
9259e8c more indentation fixes
Bozhidar Batsov authored
133 x = Math.sin(y)
134 array.delete e
dc31232 initial version
Bozhidar Batsov authored
135
136 * Prefer {...} over do...end for single-line blocks. Avoid using {...} for multi-line blocks. Always use do...end for
137 "control flow" and "method definitions" (e.g. in Rakefiles and
138 certain DSLs.) Avoid do...end when chaining.
139
140 * Avoid **return** where not required.
141
9259e8c more indentation fixes
Bozhidar Batsov authored
142 # bad
143 def some_method(some_arr)
144 return some_arr.size
145 end
dc31232 initial version
Bozhidar Batsov authored
146
9259e8c more indentation fixes
Bozhidar Batsov authored
147 # good
148 def some_method(some_arr)
149 some_arr.size
150 end
dc31232 initial version
Bozhidar Batsov authored
151
152 * Avoid line continuation (\\) where not required. In practice avoid using line continuations at all.
153
9259e8c more indentation fixes
Bozhidar Batsov authored
154 # bad
155 result = 1 + \
156 2
dc31232 initial version
Bozhidar Batsov authored
157
9259e8c more indentation fixes
Bozhidar Batsov authored
158 # good
159 result = 1 \
160 + 2
dc31232 initial version
Bozhidar Batsov authored
161
162 * Using the return value of = is okay:
163
9259e8c more indentation fixes
Bozhidar Batsov authored
164 if v = array.grep(/foo/) ...
dc31232 initial version
Bozhidar Batsov authored
165
166 * Use ||= freely.
167
9259e8c more indentation fixes
Bozhidar Batsov authored
168 # set name to Bozhidar, only if it's nil or false
169 name ||= "Bozhidar"
dc31232 initial version
Bozhidar Batsov authored
170
171 * Avoid using Perl-style global variables(like $0-9, $`, ...)
172
173 ## Naming
174
175 * Use snake_case for methods.
176 * Use CamelCase for classes and modules. (Keep acronyms like HTTP,
177 RFC, XML uppercase.)
178 * Use SCREAMING_SNAKE_CASE for other constants.
179 * The length of an identifier determines its scope. Use one-letter variables for short block/method parameters, according to this scheme:
180
9259e8c more indentation fixes
Bozhidar Batsov authored
181 a,b,c: any object
182 d: directory names
183 e: elements of an Enumerable
184 ex: rescued exceptions
185 f: files and file names
186 i,j: indexes
187 k: the key part of a hash entry
188 m: methods
189 o: any object
190 r: return values of short methods
191 s: strings
192 v: any value
193 v: the value part of a hash entry
194 x,y,z: numbers
dc31232 initial version
Bozhidar Batsov authored
195
196 And in general, the first letter of the class name if all objects are of that type.
197
198 * When using **inject** with short blocks, name the arguments **|a, e|** (mnemonic: accumulator, element)
199 * When defining binary operators, name the argument "other".
9259e8c more indentation fixes
Bozhidar Batsov authored
200 def +(other)
201 # body omitted
202 end
dc31232 initial version
Bozhidar Batsov authored
203 * Prefer **map** over *collect*, **find** over *detect*, **find_all** over *select*, **size** over *length*. This is not a hard requirement, though - if
204 the use of the alias enhances readability - it's ok to use it.
205
206 ## Comments
207
208 * Write self documenting code and ignore the rest of this section.
209 * Comments longer than a word are capitalized and use punctuation. Use two spaces after periods.
210 * Avoid superfluous comments.
211 * Keep existing comments up-to-date - no comment is better than an outdated comment.
212
213 ## Misc
214
215 * Write **ruby -w** safe code.
216 * Avoid hashes-as-optional-parameters. Does the method do too much?
217 * Avoid long methods (longer than 10 LOC). Ideally most methods will be shorter than 5 LOC. Empty line do not contribute to the relevant LOC.
218 * Avoid long parameter lists (more than 3-4 params).
219 * Use **def self.method** to define singleton methods. This makes the methods more resistent to refactoring changes.
220
9259e8c more indentation fixes
Bozhidar Batsov authored
221 class TestClass
222 # bad
223 def TestClass.some_method
224 # body omitted
225 end
dc31232 initial version
Bozhidar Batsov authored
226
9259e8c more indentation fixes
Bozhidar Batsov authored
227 # good
228 def self.some_other_method
229 # body omitted
230 end
dc31232 initial version
Bozhidar Batsov authored
231 end
232
233 * Add "global" methods to Kernel (if you have to) and make them private.
234 * Avoid **alias** when **alias_method** will do.
235 * Use **OptionParser** for parsing complex command line options and
236 **ruby -s* for trivial command line options.
2289a47 fixed a typo
Bozhidar Batsov authored
237 * Write for Ruby 1.9. Don't use legacy Ruby 1.8 constructs.
dc31232 initial version
Bozhidar Batsov authored
238 * use the new JavaScript literal hash syntax
239 * use the new lambda syntax
240 * methods like **inject** now accept methods names as arguments - `[1, 2, 3].inject(:+)`
241 * Avoid needless metaprogramming.
242
243 ## Design
244
245 * Code in a functional way, avoid mutation when it makes sense.
246 * Do not mutate arguments unless that is the purpose of the method.
247 * Do not mess around in core classes when writing libraries. (do not monkey patch them)
248 * Do not program defensively. See this [article](http://www.erlang.se/doc/programming_rules.shtml#HDR11.) for more details.
249 * Keep the code simple (subjective, but still...). Each method should have a single well-defined responsibility.
250 * Avoid more than 3 Level of block nesting.
251 * Don't overdesign. Overly complex solutions tend to be brittle and hard to maintain.
252 * Don't underdesign. A solution to a problem should be as simple as possible... but it should be simpler than that. Poor initial design
253 can lead to a lot of problems in the future.
254 * Be consistent. In an ideal world - be consistent with the points listed here in this guidelines.
255 * Use common sense.
Something went wrong with that request. Please try again.