]> www.ginac.de Git - ginac.git/blob - doc/CodingStyle
Merge some cosmetic patches.
[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:2011(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:
212
213         vector<int> vi;
214         vector<list<int>> vli;
215
216 '*' and '&' in the declaration of pointer-to and reference-to variables
217 have a space before, but not after them:
218
219         int *p;
220         int &r;
221
222 There is still an ongoing debate amongst GiNaC developers whether reference
223 parameters should be written as "foo(string &s)" or "foo(string & s)". :-)
224
225 The following section has additional examples for the proper use of
226 whitespace.
227
228
229 4. Braces
230 ---------
231
232 One word: K&R, also known as "One True Brace Style", suitably extended for
233 C++. The opening brace goes at the end of the line, except for function
234 bodies. Really short functions can be written in one single line.
235
236         if (a == b) {
237                 // do something
238         } else if (a > b) {
239                 // do something else
240         } else {
241                 // must be a < b
242         }
243
244         for (int i = 0; i < 5; ++i) {
245                 // "++i" is preferred over "i++" because, in the case of
246                 // overloaded operators, the prefix "++" is the simpler one
247                 // (the postfix "++" usually has to use a temporary variable
248                 // to save the previous state of the object for returning
249                 // it to the caller)
250         }
251
252         while (a < b) {
253                 // loop body
254         }
255
256         do {
257                 // loop body
258         } while (a < b);
259
260         switch (x) {
261         case 0:
262                 // first case
263                 break;
264         case 1:
265                 // second case
266                 break;
267         default:
268                 // default case
269                 break;
270         }
271
272         try {
273                 // do something dangerous
274         } catch (std::exception &e) {
275                 // we're caught
276         } catch (...) {
277                 // catchall
278         }
279
280         class foo {
281         public:
282                 foo(int i) : x(i)
283                 {
284                         // under construction
285                 }
286
287                 int get_x() const { return x; }
288
289         protected:
290                 void schwupp(char c);
291
292         private:
293                 int x;
294         };
295
296         namespace bar {
297                 // a foo by any other name...
298         }
299
300         void foo::schwupp(char c)
301         {
302                 // diwupp
303         }
304
305 Also take note of the use of whitespace in the above examples.
306
307
308 5. Naming
309 ---------
310
311 C++ identifiers (names of classes, types, functions, variables, etc.) should
312 not contain any uppercase characters. Preprocessor macros (anything that is
313 "#define"d), on the other hand, should not contain any lowercase characters.
314 There are some exceptions however, like "Li()" and "is_ex_the_function()"
315 (a macro). Not to mention the "GiNaC" namespace...
316
317 Names that consist of multiple words should use underscores to separate the
318 words (for example, "construct_from_int").
319
320 Don't use naming conventions such as "Hungarian notation" where the type,
321 scope, or context of an identifier is encoded in its name as a prefix,
322 like "T" or "C" for classes ("TList"), "f" or "m" for member variables, etc.
323 Try to follow the existing naming conventions in GiNaC.
324
325 Names of C++ source files end in ".cpp" (not ".C", ".cc", or ".cxx").
326 Names of header files end in ".h" (not ".hpp", ".H", ".hh", or ".hxx").
327
328
329 6. Namespaces
330 -------------
331
332 Don't place "using namespace std;", "using std::vector;" or anything like this
333 into public library header files. Doing so would force the import of all or
334 parts of the "std" namespace upon all users of the library, even if they don't
335 want it. Always fully qualify identifiers in the headers.
336
337 Definitions that are only used internally within the library but have to be
338 placed in a public header file for one reason or another should be put into
339 a namespace called "internal" inside the "GiNaC" namespace.
340
341
342 7. Miscellaneous Conventions
343 ----------------------------
344
345 Don't put the expression after a "return" statement in parentheses. It's
346 "return x;", not "return (x);" or "return(x);".
347
348 Don't put an empty "return;" statement at the end of a function that doesn't
349 return a value.
350
351 Try to put declarations of local variables close to the point where they are
352 used for the first time. C++ is not like C, where all declarations have to
353 be at the beginning of a block.
354
355 It's "const string &s", not "string const &s".
356
357 "goto" labels (if you have to use them) always start at column 1.
358
359 Don't deliberately modify code to dodge compiler warnings, unless it
360 clarifies the code in question to a human reader. This includes the use
361 of "UNUSED()" macros and similar contraptions.
362
363 Don't use more than two consecutive empty lines. Use single empty lines to
364 separate logical blocks of code (preferably, each of these blocks also has an
365 explanatory comment in front). Use two lines when you feel that one line is
366 not enough (to separate two functions, for example). But not more.
367
368
369 8. Documentation
370 ----------------
371
372 Every class, class member, and function definition should have a comment
373 in doxygen format (Javadoc style) in front of it, explaining the object's
374 purpose.
375
376 Comments inside functions should give the reader a general idea of the
377 algorithms used in the function, and describe the pragmatics behind the
378 code. To quote Linus Torvalds: "You want your comments to tell WHAT your
379 code does, not HOW.".
380
381 If your algorithms are covered in detail in some paper or thesis, it's a
382 good idea to put in a short bibliographical note.