tufte layout files:
[lyx.git] / development / coding / Rules
blob68846a668fd6aa227a20292fd28e4d7da5aabb86
1 Rules for the code in LyX
2 -------------------------
3 [updated from the C++STYLE distributed with the GNU C++ Standard]
5 The aim of this file is to serve as a guide for the developers, to aid
6 us to get clean and uniform code. This document is incomplete.
8 We really like to have new developers joining the LyX Project. However,
9 we have had problems in the past with developers leaving the
10 project and their contributed code in a far from perfect state. Most
11 of this happened before we really became aware of these issues,
12 but still, we don't want it to happen again. So we have put together
13 some guidelines and rules for the developers.
16 General
17 -------
19 These guidelines should save us a lot of work while cleaning up the code and
20 help us to have quality code. LyX has been haunted by problems coming from
21 unfinished projects by people who have left the team. Those problems will
22 hopefully disappear if the code is easy to hand over to somebody else.
24 In general, if you want to contribute to the main source, we expect at least
25 that you:
27 - the most important rule first: kiss (keep it simple stupid), always
28   use a simple implementation in favor of a more complicated one.
29   This eases maintenance a lot.
30 - write good C++ code: Readable, well commented and taking advantage of the
31   OO model. Follow the formatting guidelines. See Formatting.
32 - adapt the code to the structures already existing in LyX, or in the case
33   that you have better ideas, discuss them on the developer's list before
34   writing the code.
35 - take advantage of the C++ standard library. especially don't use
36   custom containers when a standard container is usable; learn to use
37   the algorithms and functors in the standard library.
38 - be aware of exceptions and write exception safe code. See Exceptions.
39 - document all variables, methods, functions, classes etc. We are
40   using the source documentation program doxygen, a program that handles
41   javadoc syntax, to document sources. You can download doxygen from :
43   http://www.stack.nl/~dimitri/doxygen/
45 - we have certain code constructs that we try to follow. See Code
46   Constructs.
49 Submitting Code
50 ---------------
52 It is implicitly understood that all patches contributed to The LyX
53 Project is under the Gnu General Public License, version 2 or later.
54 If you have a problem with that, don't contribute code.
56 Also please don't just pop up out of the blue with a huge patch (or
57 small) that changes something substantial in LyX. Always discuss your
58 ideas with the developers on the developer's mailing list.
60 When you create the patch, please use "diff -up" since we find that a
61 lot easier to read than the other diff formats. Also please do not
62 send patches that implements or fixes several different things; several
63 patches is a much better option.
65 We also require you to provide a commit message entry with every patch,
66 this describes in detail what the patch is doing.
69 Code Constructs
70 ---------------
72 We have several guidelines on code constructs, some of these exist to
73 make the code faster, others to make the code clearer. Yet others
74 exist to allow us to take advantage of the strong type checking
75 in C++.
77 - Declaration of variables should wait as long as possible. The rule
78   is: "Don't declare it until you need it." In C++ there are a lot of
79   user defined types, and these can very often be expensive to
80   initialize. This rule connects to the next rule too.
82 - Declare the variable as const if you don't need to change it. This
83   applies to POD types like int as well as classes.
85 - Make the scope of a variable as small as possible.
87 - Make good use of namespaces. Prefer anonymous namespaces to declaring
88   "static" for file scope.
90 - Prefer preincrement to postincrement whenever possible.
91   Preincrement has potential of being faster than postincrement. Just
92   think about the obvious implementations of pre/post-increment. This
93   rule applies to decrement too.
95         ++T;
96         --U;
97         -NOT-
98         T++; // not used in LyX
99         U--; // not used in LyX
101 - Try to minimize evaluation of the same code over and over. This is
102   aimed especially at loops.
104         Container::iterator end = large.end();
105         for (Container::iterator it = large.begin(); it != end; ++it) {
106                 ...;
107         }
108         -NOT-
109         for (Container::iterator it = large.begin();
110              it != large.end(); ++it) {
111                 ...;
112         }
114 - For functions and methods that return a non-POD type T, return T
115   const instead. This gives better type checking, and will give a
116   compiler warning when temporaries are used wrongly.
118         T const add(...);
119         -NOT-
120         T add(...);
122 - Avoid using the default cases in switch statements unless you have
123   too. Use the correct type for the switch expression and let the
124   compiler ensure that all cases are exhausted.
126         enum Foo {
127                 FOO_BAR1,
128                 FOO_BAR2
129         };
130         Foo f = ...;
131         switch (f) {
132         case FOO_BAR1: ...; break;
133         case FOO_BAR2: ...; break;
134         default: ...; break; // not needed and would shadow a wrong use of Foo
135         }
138 Exceptions
139 ----------
141 Be aware of the presence of exceptions. One important thing to realize
142 is that you often do not have to use throw, try or catch to be exception
143 safe. Let's look at the different types of exceptions safety: (These are
144 taken from Herb Sutter's book[ExC++]
147 1. Basic guarantee: Even in the presence of exceptions thrown by T or
148         other exceptions, Stack objects don't leak resources.
149         Note that this also implies that the container will be
150         destructible and usable even if an exception is thrown while
151         performing some container operation. However, if an exception
152         is thrown, the container will be in a consistent, but not
153         necessarily predictable, state. Containers that support the
154         basic guarantee can work safely in some settings.
156 2. Strong guarantee: If an operation terminates because of an
157         exception, program state will remain unchanged.
158         This always implies commit-or-rollback semantics, including
159         that no references or iterators into the container be
160         invalidated if an operation fails. For example, if a Stack
161         client calls Top and then attempts a Push that fails because
162         of an exception, then the state of the Stack object must be
163         unchanged and the reference returned from the prior call to
164         Top must still be valid. For more information on these
165         guarantees, see Dave Abrahams's documentation of the SGI
166         exception-safe standard library adaption at:
168         http://www.stlport.org/doc/exception_safety.html
170         Probably the most interesting point here is that when you
171         implement the basic guarantee, the strong guarantee often
172         comes for free. For example, in our Stack implementation,
173         almost everything we did was needed to satisfy just the basic
174         guarantee -- and what's presented above very nearly satisfies
175         the strong guarantee, with little of no extra work. Not half
176         bad, considering all the trouble we went to.
178         In addition to these two guarantees, there is one more
179         guarantee that certain functions must provide in order to make
180         overall exception safety possible:
182 3. Nothrow guarantee: The function will not emit an exception under any
183         circumstances.
184         Overall exception safety isn't possible unless certain
185         functions are guaranteed not to throw. In particular, we've
186         seen that this is true for destructors; later in this
187         miniseries, we'll see that it's also needed in certain helper
188         functions, such as Swap().
191 For all cases where we might be able to write exception safe functions
192 without using try, throw or catch we should do so. In particular we
193 should look over all destructors to ensure that they are as exception
194 safe as possible.
197 Formatting
198 ----------
200 * Only one declaration on each line.
201         int a;
202         int b;
203         -NOT-
204         int a, b; // not used in LyX
205   This is especially important when initialization is done at the same
206   time:
207         string a = "Lars";
208         string b = "Gullik";
209         -NOT-
210         string a = "Lars", b = "Gullik"; // not used in LyX
212         [Note that 'string a = "Lars"' is formally calling a copy constructor 
213         on a temporary constructed from a string literal and therefore has the
214         potential of being more expensive then direct construction by
215         'string a("Lars")'. However the compiler is allowed to elide the copy
216         (even if it had side effects), and modern compilers typically do so.
217         Given these equal costs, LyX code favours the '=' idiom as it is in
218         line with the traditional C-style initialization, _and_ cannot be
219         mistaken as function declaration, _and_ reduces the level of nested
220         parantheses in more initializations.]
221         
223 * Pointers and references
224         char * p = "flop";
225         char & c = *p;
226         -NOT-
227         char *p = "flop"; // not used in LyX
228         char &c = *p;     // not used in LyX
230   Some time ago we had a huge discussion on this subject and after
231   convincing argumentation from Asger this is what we decided. Also note
232   that we will have:
233         char const * p;
234         -NOT-
235         const char * p; // not used in LyX
237 * Operator names and parentheses
238         operator==(type)
239         -NOT-
240         operator == (type)  // not used in LyX
242   The == is part of the function name, separating it makes the
243   declaration look like an expression.
245 * Function names and parentheses
246         void mangle()
247         -NOT-
248         void mangle ()  // not used in LyX
250 * Enumerators
251         enum Foo {
252                 FOO_ONE = 1,
253                 FOO_TWO = 2,
254                 FOO_THREE = 3
255         };
256         -NOT-
257         enum { one = 1, two = 2, three 3 }; // not used in LyX
258         -NOT-
259         enum {
260                 One = 1,
261                 Two = 2,
262                 Three = 3
263         };
265 * Null pointers
267         Using a plain 0 is always correct and least effort to type. So:
269         void * p = 0;
270         -NOT-
271         void * p = NULL; // not used in LyX
272         -NOT-
273         void * p = '\0'; // not used in LyX
274         -NOT-
275         void * p = 42 - 7 * 6; // not used in LyX
277         Note: As an exception, imported third party code as well as code
278         interfacing the "native" APIs (src/support/os_*) can use NULL.
280 * Naming rules for classes
282   - Use descriptive but simple and short names. Do not abbreviate.
284   - Class names are usually capitalized, and function names lowercased.
285     Enums are named like Classes, values are usually in lower-case.
287   - Long variables are named like thisLongVariableName.
289   New types are capitalized, so this goes for typedefs, classes, structs
290   and enums.
292 * Formatting
294   - Adapt the formatting of your code to the one used in the
295     other parts of LyX. In case there is different formatting for
296     the same construct, use the one used more often.
298 * Use existing structures
300   - Use string wherever possible. LyX will someday move to Unicode, and
301     that will be easy if everybody uses string now. Unicode strings 
302     should prefer using docstring instead of UTF-8 encoded std::string.
304   - Check out the filename and path tools in filetools.h
306   - Check out the string tools in lstring.h.
308   - Use the LyXErr class to report errors and messages using
309     the lyxerr instantiation.
311   [add description of other existing structures]
314 * Declarations
316   - Use this order for the access sections of your class: public,
317     protected, private. The public section is interesting for every
318     user of the class. The private section is only of interest for the
319     implementors of the class (you). [Obviously not true since this is
320     for developers, and we do not want one developer only to be able to
321     read and understand the implementation of class internals. Lgb]
323   - Avoid declaring global objects in the declaration file of the class.
324     If the same variable is used for all objects, use a static member.
326   - Avoid global or static variables.
329 * File headers
331   - If you create a new file, the top of the file should look something
332     like this :
334   /**
335    * \file NewFile.cpp
336    * This file is part of LyX, the document processor.
337    * Licence details can be found in the file COPYING.
338    *
339    * \author Kaiser Sose
340    *
341    * Full author contact details are available in file CREDITS
342    */
344 * Documentation
346   - The documentation is generated from the header files.
347   - You document for the other developers, not for yourself.
348   - You should document what the function does, not the implementation.
349   - in the .cpp files you document the implementation.
350   - Single line description (///), multiple lines description (/** ... */)
351   - see the doxygen webpage referenced above
354 * NAMING RULES FOR USER-COMMANDS
356   Here's the set of rules to apply when a new command name is introduced:
358   1) Use the object.event order. That is, use `word-forward' instead of
359      `forward-word'.
360   2) Don't introduce an alias for an already named object. Same for events.
361   3) Forward movement or focus is called `forward' (not `right').
362   4) Backward movement or focus is called `backward' (not `left').
363   5) Upward movement of focus is called `up'.
364   6) Downward movement is called `down'.
365   7) The begin of an object is called `begin' (not `start').
366   8) The end of an object is called `end'.
369  *************************************************************
371  How to create class interfaces.
372  (a.k.a How Non-Member Functions Improve Encapsulation)
373  ======================================================
375         I recently read an article by Scott Meyers in C/C++ User's
376 Journal (Vol.18,No.2), where he makes a strong case on how non-member
377 functions makes classes more encapsulated, not less. Just skipping
378 to the core of this provides us with the following algorithm for
379 deciding what kind of function to add to a class interface:
381         - We need to add a function f to the class C's API.
383         if (f needs to be virtual)
384                 make f a member function of C;
385         else if (f is operator>> or operator<<) {
386                 make f a non-member function;
387                 if (f needs access to non-public members of C)
388                         make f a friend of C;
389         } else if (f needs type conversions on its left-most argument) {
390                 make f a non-member function;
391                 if (f needs access to non-public members of C)
392                         make f a friend of C;
393         } else if (f can be implemented via C's public interface)
394                 make f a non-member function;
395         else
396                 make f a member function of C;
398 (I'll fill in more from Scott Meyers article when time allows.)
400 References
401 ----------
403 [ExC++] Sutter, Herb. Exceptional C++: 47 engineering puzzles,
404         programming problems, and solutions. ISBN 0-201-61562-2