]> www.ginac.de Git - ginac.git/blob - doc/CodingStyle
* Avoid suprious cross-references caused by @strong{Note:}.
[ginac.git] / doc / CodingStyle
1 GiNaC Coding Style
2 ==================
3
4 This document attempts to describe the preferred coding style for GiNaC.
5
6
7 0. Preface
8 ----------
9
10 Different people have different ideas of how source code should be formatted
11 to be most beautiful and/or useful to work with. GiNaC itself was developed
12 by a group of people whose ideas on these matters differed in some details.
13 It also evolved over the course of the years, and received contributions
14 from outside. As a result, the GiNaC source is not in all places 100%
15 consistent with the rules laid out in this document. Old code will
16 eventually be converted, however. New code should always be in this style.
17
18 Sometimes it's also not possible (or desirable) to give precise rules for
19 every single occasion. Should you write "2*x+y", "2*x + y" or "2 * x + y"?
20 We don't know. We also don't care (much). Use your own discretion.
21
22 This document does not intend to codify the "perfect" programming style, but
23 please try to follow these rules. It will make our (and your) lives easier. :-)
24
25
26 1. General Conventions
27 ----------------------
28
29 Any code in GiNaC should comply to the C++ standard, as defined by ISO/IEC
30 14882:1998(E). Don't use compiler-specific language extensions unless they
31 are surrounded by appropriate "#ifdef"s, and you also provide a compliant
32 version of the code in question for other compilers.
33
34 Source code formatting assumes a fixed-width font. You do not need to restrict
35 yourself to 80 columns, except in comment blocks, but try to avoid overlong
36 lines.
37
38
39 2. Indentation and Alignment
40 ----------------------------
41
42 Short version: Indentation and alignment should be tab-size independent. Use
43 one Tab for each indentation level. Use spaces for aligning portions of code.
44
45 Explanation: "Indentation" and "alignment" are two related, but different
46 things. To indent means to set a section of code in from the left margin,
47 to facilitate distinguishing "contained" sections (such as a sequence of lines
48 inside an "if" statement) from their "containers" (in this case, the "if"
49 statement itself). For nested constructs, indentation is carried out in
50 several levels:
51
52 No indentation
53 Begin 1
54         One level of indentation
55         Begin 2
56                 Two levels of indentation
57                 etc.
58         End 2
59 End 1
60
61 To align, on the other hand, means to make parts of the text start on the
62 same column on the screen, to make it look more tidy and clear.
63
64 Here is an example that features both indentation and alignment:
65
66 class person {
67         string name;  // person's full name
68         int age;      // age in years
69 };
70
71 The inner part of the class definition (the part between the braces) is
72 _indented_ by one level. The comments at the end of these two lines are
73 _aligned_ to put them directly below each other on the screen.
74
75 Now why are we making such a fuss about the difference between these two?
76 This is where the "tab-size independent" part comes in.
77
78 Both indentation and alignment are often done with Tab characters ('\t' or
79 ASCII 0x09). And in theory, that would be the best and logical choice.
80 Unfortunately, there is no general agreement about the placement of the
81 tabulator stops in effect.
82
83 Traditionally, tab stops are every 8 characters. Many programmers indent with
84 Tabs because it's only one keypress, but they feel that a tab-size of 8
85 pushes the code too far to the right, so they change it to 4 characters (or
86 some other value) in their editors. When alignment is also performed with
87 tabs this results in misaligned code unless the tab-size is set to the
88 exact same value the author of the code used.
89
90 Take the "person" class definition from above as an example (here and in
91 the following, ':' represents a Tab, while '.' represents a Space). Assume
92 that we had done both indentation and alignment with Tabs, with a tab-size
93 of 8:
94
95 |-------|-------|-------|-------|-------|-------|------- <- tab stops
96 class person {
97 ::::::::string name;::::// person's full name
98 ::::::::int age;::::::::// age in years
99 };
100
101 Now somebody who prefers a tab-size of 4 looks at the code:
102
103 |---|---|---|---|---|---|---|---|---|---|---|---|---|--- <- tab stops
104 class person {
105 ::::string name;::::// person's full name
106 ::::int age;::::// age in years
107 };
108
109 The indentation is still correct, but the two comments are now misaligned.
110
111 The default indentation mode of the Emacs editor is even worse: it mixes
112 Tabs (which it assumes to be of size 4) and spaces for both indentation and
113 alignment, with an effective amount of 2 character widths per indentation
114 level. The resulting code usually looks like a complete mess for any tab-size
115 setting other than 4.
116
117 So, how do you make it tab-size independent? One solution would be to not
118 use any Tab characters at all. This, however, would hard-code the amount
119 of space used for indentation, something which so many people disagree
120 about.
121
122 Instead, we adopted a different approach in GiNaC: Tabs are used exclusively
123 for indentation (one Tab per level); spaces are used for alignment. This
124 gets you the best of both worlds: It allows every programmer to change the
125 tab-size (and thus, the visual amount of indentation) to his/her own desire,
126 but the code still looks OK at any setting.
127
128 This is how our class definition should be entered using this scheme
129 (remember, ':' are Tabs, '.' are Spaces):
130
131 |-------|-------|-------|-------|-------|-------|------- <- tab stops
132 class person {
133 ::::::::string name;..// person's full name
134 ::::::::int age;......// age in years
135 };
136
137 8 characters indentation are too much for you? No problem. Just change the
138 tab-size, and it still looks good:
139
140 |---|---|---|---|---|---|---|---|---|---|---|---|---|--- <- tab stops
141 class person {
142 ::::string name;..// person's full name
143 ::::int age;......// age in years
144 };
145
146 Some more examples (shown with a tab-size of 4):
147
148 // here, we have aligned the parameter declarations
149 int foo(int i1, int i2, int i3,
150 ........string s1, string s2,
151 ........vector<int> &result)
152 {
153 ::::// inside the function, one level of indentation
154 ::::if (i1 == i2) {
155 ::::::::// inside the "if", two levels of indentation
156 ::::::::return 0;
157 ::::}
158 ::::// outside the "if", one level again
159
160 ::::// indentation is also used here:
161 ::::static int fibonacci[] = {
162 ::::::::1, 2, 3, 5, 8, 13,
163 ::::::::21, 34, 55, 89, 144
164 ::::};
165
166 ::::// and here:
167 ::::int x = bar(
168 ::::::::i1 - i2,
169 ::::::::i2 - i3,
170 ::::::::i3 - i1
171 ::::);
172
173 ::::// continuation lines, however, are aligned, not indented:
174 ::::cout << "i1 = " << i1 << ", i2 = " << i2 << ", i3 = " << i3
175 ::::.....<< ", string1 = " << s1
176 ::::.....<< ", string2 = " << s2 << endl;
177
178 ::::if (s1 == s2)
179 ::::::::return i1;.......// these two comments
180 ::::else
181 ::::::::return i2 + i3;..// are also aligned
182 }
183
184
185 3. Whitespace
186 -------------
187
188 A ',' is always followed by one space:
189
190         int a[] = {1, 2, 3};
191
192 There is no space between a function name and the following opening
193 parenthesis. There are no spaces after the opening and before the closing
194 parentheses, either:
195
196         x = foo(i1, i2, i3);
197
198 There is, however, one space after "if", "for", "while", "switch", and
199 "catch" (these are not functions, after all):
200
201         if (i1 == i2)
202
203 You should place one space before and behind any binary operator (except
204 '::', '[]', '.', '.*', '->' and '->*'; for ',' see above). There is no space
205 after (or before, in the case of postfix '++' and '--') unary operators:
206
207         a = b[i] + *p++;
208         x = -(y + z) / 2;
209
210 There are no spaces around the '<' and '>' used to designate template
211 parameters. Unfortunately, a design flaw in C++ requires putting a space
212 between two consecutive closing '>'s. We suggest that in this case you also
213 put a space after the opening '<':
214
215         vector<int> vi;
216         vector< list<int> > vli;
217
218 '*' and '&' in the declaration of pointer-to and reference-to variables
219 have a space before, but not after them:
220
221         int *p;
222         int &r;
223
224 There is still an ongoing debate amongst GiNaC developers whether reference
225 parameters should be written as "foo(string &s)" or "foo(string & s)". :-)
226
227 The following section has additional examples for the proper use of
228 whitespace.
229
230
231 4. Braces
232 ---------
233
234 One word: K&R, also known as "One True Brace Style", suitably extended for
235 C++. The opening brace goes at the end of the line, except for function
236 bodies. Really short functions can be written in one single line.
237
238         if (a == b) {
239                 // do something
240         } else if (a > b) {
241                 // do something else
242         } else {
243                 // must be a < b
244         }
245
246         for (int i = 0; i < 5; ++i) {
247                 // "++i" is preferred over "i++" because, in the case of
248                 // overloaded operators, the prefix "++" is the simpler one
249                 // (the postfix "++" usually has to use a temporary variable
250                 // to save the previous state of the object for returning
251                 // it to the caller)
252         }
253
254         while (a < b) {
255                 // loop body
256         }
257
258         do {
259                 // loop body
260         } while (a < b);
261
262         switch (x) {
263         case 0:
264                 // first case
265                 break;
266         case 1:
267                 // second case
268                 break;
269         default:
270                 // default case
271                 break;
272         }
273
274         try {
275                 // do something dangerous
276         } catch (std::exception &e) {
277                 // we're caught
278         } catch (...) {
279                 // catchall
280         }
281
282         class foo {
283         public:
284                 foo(int i) : x(i)
285                 {
286                         // under construction
287                 }
288
289                 int get_x() const { return x; }
290
291         protected:
292                 void schwupp(char c);
293
294         private:
295                 int x;
296         };
297
298         namespace bar {
299                 // a foo by any other name...
300         }
301
302         void foo::schwupp(char c)
303         {
304                 // diwupp
305         }
306
307 Also take note of the use of whitespace in the above examples.
308
309
310 5. Naming
311 ---------
312
313 C++ identifiers (names of classes, types, functions, variables, etc.) should
314 not contain any uppercase characters. Preprocessor macros (anything that is
315 "#define"d), on the other hand, should not contain any lowercase characters.
316 There are some exceptions however, like "Li()" and "is_ex_the_function()"
317 (a macro). Not to mention the "GiNaC" namespace...
318
319 Names that consist of multiple words should use underscores to separate the
320 words (for example, "construct_from_int").
321
322 Don't use naming conventions such as "Hungarian notation" where the type,
323 scope, or context of an identifier is encoded in its name as a prefix,
324 like "T" or "C" for classes ("TList"), "f" or "m" for member variables, etc.
325 Try to follow the existing naming conventions in GiNaC.
326
327 Names of C++ source files end in ".cpp" (not ".C", ".cc", or ".cxx").
328 Names of header files end in ".h" (not ".hpp", ".H", ".hh", or ".hxx").
329
330
331 6. Namespaces
332 -------------
333
334 Don't place "using namespace std;", "using std::vector;" or anything like this
335 into public library header files. Doing so would force the import of all or
336 parts of the "std" namespace upon all users of the library, even if they don't
337 want it. Always fully qualify identifiers in the headers.
338
339 Definitions that are only used internally within the library but have to be
340 placed in a public header file for one reason or another should be put into
341 a namespace called "internal" inside the "GiNaC" namespace.
342
343
344 7. Miscellaneous Conventions
345 ----------------------------
346
347 Don't put the expression after a "return" statement in parentheses. It's
348 "return x;", not "return (x);" or "return(x);".
349
350 Don't put an empty "return;" statement at the end of a function that doesn't
351 return a value.
352
353 Try to put declarations of local variables close to the point where they are
354 used for the first time. C++ is not like C, where all declarations have to
355 be at the beginning of a block.
356
357 It's "const string &s", not "string const &s".
358
359 "goto" labels (if you have to use them) always start at column 1.
360
361 Don't deliberately modify code to dodge compiler warnings, unless it
362 clarifies the code in question to a human reader. This includes the use
363 of "UNUSED()" macros and similar contraptions.
364
365 Don't use more than two consecutive empty lines. Use single empty lines to
366 separate logical blocks of code (preferably, each of these blocks also has an
367 explanatory comment in front). Use two lines when you feel that one line is
368 not enough (to separate two functions, for example). But not more.
369
370
371 8. Documentation
372 ----------------
373
374 Every class, class member, and function definition should have a comment
375 in doxygen format (Javadoc style) in front of it, explaining the object's
376 purpose.
377
378 Comments inside functions should give the reader a general idea of the
379 algorithms used in the function, and describe the pragmatics behind the
380 code. To quote Linus Torvalds: "You want your comments to tell WHAT your
381 code does, not HOW.".
382
383 If your algorithms are covered in detail in some paper or thesis, it's a
384 good idea to put in a short bibliographical note.