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