README.Coding: add examples for good and bad comments
[samba.git] / README.Coding
1 Coding conventions in the Samba tree
2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4 .. contents::
5
6 ===========
7 Quick Start
8 ===========
9
10 Coding style guidelines are about reducing the number of unnecessary
11 reformatting patches and making things easier for developers to work
12 together.
13 You don't have to like them or even agree with them, but once put in place
14 we all have to abide by them (or vote to change them).  However, coding
15 style should never outweigh coding itself and so the guidelines
16 described here are hopefully easy enough to follow as they are very
17 common and supported by tools and editors.
18
19 The basic style, also mentioned in prog_guide4.txt, is the Linux kernel
20 coding style (See Documentation/CodingStyle in the kernel source tree). This
21 closely matches what most Samba developers use already anyways, with a few
22 exceptions as mentioned below.
23
24 But to save you the trouble of reading the Linux kernel style guide, here
25 are the highlights.
26
27 * Maximum Line Width is 80 Characters
28   The reason is not about people with low-res screens but rather sticking
29   to 80 columns prevents you from easily nesting more than one level of
30   if statements or other code blocks.  Use source3/script/count_80_col.pl
31   to check your changes.
32
33 * Use 8 Space Tabs to Indent
34   No whitespace fillers.
35
36 * No Trailing Whitespace
37   Use source3/script/strip_trail_ws.pl to clean up your files before
38   committing.
39
40 * Follow the K&R guidelines.  We won't go through all of them here. Do you
41   have a copy of "The C Programming Language" anyways right? You can also use
42   the format_indent.sh script found in source3/script/ if all else fails.
43
44
45
46 ============
47 Editor Hints
48 ============
49
50 Emacs
51 -----
52 Add the follow to your $HOME/.emacs file:
53
54   (add-hook 'c-mode-hook
55         (lambda ()
56                 (c-set-style "linux")
57                 (c-toggle-auto-state)))
58
59
60 Vi
61 --
62 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
63
64 For the basic vi editor included with all variants of \*nix, add the
65 following to $HOME/.exrc:
66
67   set tabstop=8
68   set shiftwidth=8
69
70 For Vim, the following settings in $HOME/.vimrc will also deal with
71 displaying trailing whitespace:
72
73   if has("syntax") && (&t_Co > 2 || has("gui_running"))
74         syntax on
75         function! ActivateInvisibleCharIndicator()
76                 syntax match TrailingSpace "[ \t]\+$" display containedin=ALL
77                 highlight TrailingSpace ctermbg=Red
78         endf
79         autocmd BufNewFile,BufRead * call ActivateInvisibleCharIndicator()
80   endif
81   " Show tabs, trailing whitespace, and continued lines visually
82   set list listchars=tab:»·,trail:·,extends:…
83
84   " highlight overly long lines same as TODOs.
85   set textwidth=80
86   autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
87
88
89 =========================
90 FAQ & Statement Reference
91 =========================
92
93 Comments
94 --------
95
96 Comments should always use the standard C syntax.  C++
97 style comments are not currently allowed. The lines before
98 a comment should be empty. If the comment directly belongs
99 to the following code, there should be no empty line after
100 the comment. In case the comment contains a summary of
101 mutliple following code blogs.
102
103 This is good:
104
105         ...
106         int i;
107
108         /*
109          * This is a multi line comment,
110          * which explains the logical steps we have to do:
111          *
112          * 1. We need to set i=5, because...
113          * 2. We need to call complex_fn1
114          */
115
116         /* This is a one line comment about i = 5. */
117         i = 5;
118
119         /*
120          * This is a multi line comment,
121          * explaining the call to complex_fn1()
122          */
123         ret = complex_fn1();
124         if (ret != 0) {
125         ...
126
127         /**
128          * @brief This is a doxygen comment.
129          *
130          * This is a more detailed explanation of
131          * this simple function.
132          *
133          * @param[in]   param1     The parameter value of the function.
134          *
135          * @param[out]  result1    The result value of the function.
136          *
137          * @return              0 on success and -1 on error.
138          */
139         int example(int param1, int *result1);
140
141 This is bad:
142
143         ...
144         int i;
145         /*
146          * This is a multi line comment,
147          * which explains the logical steps we have to do:
148          *
149          * 1. We need to set i=5, because...
150          * 2. We need to call complex_fn1
151          */
152         /* This is a one line comment about i = 5. */
153         i = 5;
154         /*
155          * This is a multi line comment,
156          * explaining the call to complex_fn1()
157          */
158         ret = complex_fn1();
159         if (ret != 0) {
160         ...
161
162         /*This is a one line comment.*/
163
164         /* This is a multi line comment,
165            with some more words...*/
166
167         /*
168          * This is a multi line comment,
169          * with some more words...*/
170
171 Indention & Whitespace & 80 columns
172 -----------------------------------
173
174 To avoid confusion, indentations have to be tabs with length 8 (not 8
175 ' ' characters).  When wrapping parameters for function calls,
176 align the parameter list with the first parameter on the previous line.
177 Use tabs to get as close as possible and then fill in the final 7
178 characters or less with whitespace.  For example,
179
180         var1 = foo(arg1, arg2,
181                    arg3);
182
183 The previous example is intended to illustrate alignment of function
184 parameters across lines and not as encourage for gratuitous line
185 splitting.  Never split a line before columns 70 - 79 unless you
186 have a really good reason.  Be smart about formatting.
187
188
189 If, switch, & Code blocks
190 -------------------------
191
192 Always follow an 'if' keyword with a space but don't include additional
193 spaces following or preceding the parentheses in the conditional.
194 This is good:
195
196         if (x == 1)
197
198 This is bad:
199
200         if ( x == 1 )
201
202 Yes we have a lot of code that uses the second form and we are trying
203 to clean it up without being overly intrusive.
204
205 Note that this is a rule about parentheses following keywords and not
206 functions.  Don't insert a space between the name and left parentheses when
207 invoking functions.
208
209 Braces for code blocks used by for, if, switch, while, do..while, etc.
210 should begin on the same line as the statement keyword and end on a line
211 of their own. You should always include braces, even if the block only
212 contains one statement.  NOTE: Functions are different and the beginning left
213 brace should be located in the first column on the next line.
214
215 If the beginning statement has to be broken across lines due to length,
216 the beginning brace should be on a line of its own.
217
218 The exception to the ending rule is when the closing brace is followed by
219 another language keyword such as else or the closing while in a do..while
220 loop.
221
222 Good examples:
223
224         if (x == 1) {
225                 printf("good\n");
226         }
227
228         for (x=1; x<10; x++) {
229                 print("%d\n", x);
230         }
231
232         for (really_really_really_really_long_var_name=0;
233              really_really_really_really_long_var_name<10;
234              really_really_really_really_long_var_name++)
235         {
236                 print("%d\n", really_really_really_really_long_var_name);
237         }
238
239         do {
240                 printf("also good\n");
241         } while (1);
242
243 Bad examples:
244
245         while (1)
246         {
247                 print("I'm in a loop!\n"); }
248
249         for (x=1;
250              x<10;
251              x++)
252         {
253                 print("no good\n");
254         }
255
256         if (i < 10)
257                 print("I should be in braces.\n");
258
259
260 Goto
261 ----
262
263 While many people have been academically taught that "goto"s are
264 fundamentally evil, they can greatly enhance readability and reduce memory
265 leaks when used as the single exit point from a function. But in no Samba
266 world what so ever is a goto outside of a function or block of code a good
267 idea.
268
269 Good Examples:
270
271         int function foo(int y)
272         {
273                 int *z = NULL;
274                 int ret = 0;
275
276                 if (y < 10) {
277                         z = malloc(sizeof(int)*y);
278                         if (!z) {
279                                 ret = 1;
280                                 goto done;
281                         }
282                 }
283
284                 print("Allocated %d elements.\n", y);
285
286          done:
287                 if (z) {
288                         free(z);
289                 }
290
291                 return ret;
292         }
293
294
295 Checking Pointer Values
296 -----------------------
297
298 When invoking functions that return pointer values, either of the following
299 are acceptable. Use your best judgement and choose the more readable option.
300 Remember that many other persons will review it:
301
302         if ((x = malloc(sizeof(short)*10)) == NULL ) {
303                 fprintf(stderr, "Unable to alloc memory!\n");
304         }
305
306 or:
307
308         x = malloc(sizeof(short)*10);
309         if (!x) {
310                 fprintf(stderr, "Unable to alloc memory!\n");
311         }
312
313
314 Primitive Data Types
315 --------------------
316
317 Samba has large amounts of historical code which makes use of data types
318 commonly supported by the C99 standard. However, at the time such types
319 as boolean and exact width integers did not exist and Samba developers
320 were forced to provide their own.  Now that these types are guaranteed to
321 be available either as part of the compiler C99 support or from
322 lib/replace/, new code should adhere to the following conventions:
323
324   * Booleans are of type "bool" (not BOOL)
325   * Boolean values are "true" and "false" (not True or False)
326   * Exact width integers are of type [u]int[8|16|32|64]_t
327
328
329 Typedefs
330 --------
331
332 Samba tries to avoid "typedef struct { .. } x_t;" so we do always try to use
333 "struct x { .. };". We know there are still such typedefs in the code,
334 but for new code, please don't do that anymore.
335
336 Make use of helper variables
337 ----------------------------
338
339 Please try to avoid passing function calls as function parameters
340 in new code. This makes the code much easier to read and
341 it's also easier to use the "step" command within gdb.
342
343 Good Example:
344
345         char *name;
346
347         name = get_some_name();
348         if (name == NULL) {
349                 ...
350         }
351
352         ret = some_function_my_name(name);
353         ...
354
355
356 Bad Example:
357
358         ret = some_function_my_name(get_some_name());
359         ...
360