[H7] Add USE_TIMER_MGMT to H7
[betaflight.git] / docs / development / CodingStyle.md
blob3528d6be628cb7ccb35879ea3f77838eafe47937
1 # General
3 This document overrides the original Baseflight style that was referenced before.
4 This document has taken inspiration from that style, from Eclipse defaults and from Linux, as well as from some Cleanflight and Betaflight developers and existing code.
6 There are not so many changes from the old style, if you managed to find it.
8 # Formatting style
10 ## Indentation
12 [1TBS](https://en.wikipedia.org/wiki/Indentation_style#Variant:_1TBS_(OTBS)) (based K&R) indent style with 4 space indent, NO hard tabs (all tabs replaced by spaces).
14 ## Tool support
16 Any of these tools can get you pretty close:
18 Eclipse built in "K&R" style, after changing the indent to 4 spaces and change Braces after function declarations to Next line.
19 ```
20 astyle --style=kr --indent=spaces=4 --min-conditional-indent=0 --max-instatement-indent=80 --pad-header --pad-oper --align-pointer=name --align-reference=name --max-code-length=120 --convert-tabs --preserve-date --suffix=none --mode=c
21 ```
22 ```
23 indent -kr -i4 -nut
24 ```
25 (the options for these commands can be tuned more to comply even better)
27 Note: These tools are not authorative.
28 Sometimes, for example, you may want other columns and line breaks so it looks like a matrix.
30 Note2: The Astyle settings have been tested and will produce a nice result. Many files will be changed, mostly to the better but maybe not always, so use with care. 
32 ## Curly Braces
34 Functions shall have the opening brace at the beginning of the next line.
35 ```
36 int function(int x)
38     body of function
40 ```
42 All non-function statement blocks (if, switch, for) shall have the opening brace last on the same line, with the following statement on the next line.
44 Closing braces shall be but on the line after the last statement in the block.
45 ```
46 if (x is true) {
47     we do y
48     ...
50 ```
52 ```
53 switch (action) {
54 case ADD:
55     return "add";
56 case REMOVE:
57     return "remove";
58 case CHANGE:
59     return "change";
60 default:
61     return NULL;
63 ```
65 If it is followed by an `else` or `else if` that shall be on the same line, again with the opening brace on the same line.
66 ```
67 if (x is true) {
68     we do y
69     ...
70 } else {
71     we do z
72     ...
74 ```
76 Omission of "unnecessary" braces in cases where an `if` or `else` block consists only of a single statement is not permissible in any case. These "single statement blocks" are future bugs waiting to happen when more statements are added without enclosing the block in braces.
78 ## Spaces
80 Use a space after (most) keywords.  The notable exceptions are sizeof, typeof, alignof, and __attribute__, which look somewhat like functions (and are usually used with parentheses).
81 So use a space after these keywords:
82 ```
83 if, switch, case, for, do, while
84 ```
85 but not with sizeof, typeof, alignof, or __attribute__.  E.g.,
86 ```
87 s = sizeof(struct file);
88 ```
89 When declaring pointer data or a function that returns a pointer type, the preferred use of '*' is adjacent to the data name or function name and not adjacent to the type name.  Examples:
90 ```
91 char *linux_banner;
92 memparse(char *ptr, char **retptr);
93 char *match_strdup(substring_t *s);
94 ```
95 Use one space around (on each side of) most binary and ternary operators, such as any of these:
96 ```
97 =  +  -  <  >  *  /  %  |  &  ^  <=  >=  ==  !=  ?  :
98 ```
99 but no space after unary operators:
101 &  *  +  -  ~  !  sizeof  typeof  alignof  __attribute__  defined
103 no space before the postfix increment & decrement unary operators:
105 ++  --
107 no space after the prefix increment & decrement unary operators:
109 ++  --
111 and no space around the '.' and "->" structure member operators.
113 '*' and '&', when used for pointer and reference, shall have no space between it and the following variable name.
115 # typedef
117 enums that do not have a count or some other form of terminator element shall have a comma after their last element:
120 typedef enum {
121     MSP_RESULT_ACK = 1,
122     MSP_RESULT_ERROR = -1,
123     MSP_RESULT_NO_REPLY = 0,
124     MSP_RESULT_CMD_UNKNOWN = -2,
125 } mspResult_e;
128 This ensures that, if more elements are added at a later stage, only the additional lines show up in the review, making it easier to review.
130 enums with a count should have that count declared as the last item in the enumeration list,
131 so that it is automatically maintained, e.g.:
133 typedef enum {
134     PID_CONTROLLER_MW23 = 0,
135     PID_CONTROLLER_MWREWRITE,
136     PID_CONTROLLER_LUX_FLOAT,
137     PID_COUNT
138 } pidControllerType_e;
140 It shall not be calculated afterwards, e.g. using PID\_CONTROLLER\_LUX\_FLOAT + 1;
142 typedef struct definitions should include the struct name, so that the type can be forward referenced, that is in:
144 typedef struct motorMixer_s {
145     float throttle;
147     float yaw;
148 } motorMixer_t;
150 the motorMixer\_s name is required.
152 # Variables
154 ## Naming
157 Generally, descriptive lowerCamelCase names are preferred for function names, variables, arguments, etc.
158 For configuration variables that are user accessible via CLI or similar, all\_lowercase with underscore is preferred.
160 Variable names should be nouns.
162 Simple temporary variables with a very small scope may be short where it aligns with common practice.
163 Such as "i" as a temporary counter in a `for` loop, like `for (int i = 0; i < 4; i++)`.
164 Using "temporaryCounter" in that case would not improve readability.
166 ## Declarations
168 Avoid global variables.
170 Variables should be declared at the top of the smallest scope where the variable is used.
171 Variable re-use should be avoided - use distinct variabes when their use is unrelated.
172 One blank line should follow the declaration(s).
174 Hint: Sometimes you can create a block, i.e. add curly braces, to reduce the scope further.
175 For example to limit variable scope to a single `case` branch.
177 Variables with limited use may be declared at the point of first use. It makes PR-review easier (but that point is lost if the variable is used everywhere anyway).
179 ## Initialisation
181 The pattern with "lazy initialisation" may be advantageous in the Configurator to speed up the start when the initialisation is "expensive" in some way.
182 In the FC, however, it’s always better to use some milliseconds extra before take-off than to use them while flying.
184 So don't use "lazy initialisation".
186 An explicit "init" function, is preferred.
188 ## Data types
190 Be aware of the data types you use and do not trust implicit type casting to be correct.
192 Angles are sometimes represented as degrees in a float. Sometimes as decidegrees in a uint8\_t.
193 You have been warned.
195 Avoid implicit double conversions and only use float-argument functions.
197 Check .map file to make sure no conversions sneak in, and use -Wdouble-promotion warning for the compiler
199 Instead of sin() and cos(), use sin\_approx() and cos\_approx() from common/math.h.
201 Float constants should be defined with "f" suffix, like 1.0f and 3.1415926f, otherwise double conversion might occur.
203 # Functions
205 ## Naming
207 Methods that return a boolean should be named as a question, and should not change any state. e.g. 'isOkToArm()'.
209 Methods should have verb or verb-phrase names, like deletePage or save. Tell the system to 'do' something 'with' something. e.g. deleteAllPages(pageList).
211 Non-static functions should be prefixed by their class. Eg baroUpdate and not updateCompass .
213 Groups of functions acting on an 'object' should share the same prefix, e.g.
215 float biQuadFilterApply(...);
216 void biQuadFilterInit(...);
217 boolean biQuadIsReady();
219 rather than
221 float applyBiQuadFilter(...);
222 void newBiQuadLpf(...);
223 boolean isBiQuadReady();
226 ## Parameter order
228 Data should move from right to left, as in memcpy(void *dst, const void *src, size\_t size).
229 This also mimics the assignment operator (e.g. dst = src;)
231 When a group of functions act on an 'object' then that object should be the first parameter for all the functions, e.g.:
233 float biQuadFilterApply(biquad_t *state, float sample);
234 void biQuadNewLpf(biquad_t *state, float filterCutFreq, uint32_t refreshRate);
236 rather than
238 float biQuadFilterApply(float sample, biquad_t *state);
239 void biQuadNewLpf(float filterCutFreq, biquad_t *state, uint32_t refreshRate);
242 ## Declarations
244 Functions not used outside their containing .c file should be declared static (or STATIC\_UNIT\_TESTED so they can be used in unit tests).
246 Non-static functions should have their declaration in a single .h file.
248 Don't make more than necessary visible for other modules, not even types. Pre-processor macros may be used to declare module internal things that must be shared with the modules test code but otherwise hidden.
250 In the .h file:
252 #ifdef MODULENAME_INTERNALS_
253 … declarations …
254 #endif
256 In the module .c file, and in the test file but nowhere else, put `#define MODULENAME_INTERNALS_` just before including the .h file.
258 Note: You can get the same effect by putting the internals in a separate .h file.
260 ## Implementation
262 Keep functions short and distinctive.
263 Think about unit test when you define your functions. Ideally you should implement the test cases before implementing the function.
265 Never put multiple statements on a single line.
266 Never put multiple assignments on a single line.
267 Never put multiple assignments in a single statement.
269 Defining constants using pre-processor macros is not preferred.
270 Const-correctness should be enforced.
271 This allows some errors to be picked up at compile time (for example getting the order of the parameters wrong in a call to memcpy).
273 A function should only read data from the HW once in each call, and preferably all at one place.
274 For example, if gyro angle or time is needed multiple times, read once and store in a local variable.
276 Use `for` loops (rather than `do` or `while` loops) for iteration.
278 The use of `continue` or `goto` should be avoided.
279 Same for multiple `return` from a function and multiple `break` inside a `case`.
280 In general, they reduce readability and maintainability.
281 In rare cases such constructs can be justified but only when you have considered and understood the alternatives and still have a strong reason.
283 In expressions, parentheses should only be used where they are required, i.e. where operator precedence will not evaluate in the right order, or where a compiler warning is triggered without parentheses. This brings all expressions into a canonical form, and avoids the problem of different developers having different ideas of what 'easy to read' expressions are.
285 One exception to this rule is the ternary conditional operator
288 pidStabilisationEnabled = (pidControllerState == PID_STABILISATION_ON) ? true : false
291 Here, the condition shall be enclosed in braces, to make the ternary operator easier to spot when reading left to right.
293 # Includes
295 All files must include their own dependencies and not rely on includes from the included files or that some other file was included first.
297 Do not include things you are not using.
299 "[#pragma once](https://en.wikipedia.org/wiki/Pragma_once)" is preferred over "#include guards" to avoid multiple includes.
302 # Other details
304 No trailing whitespace at the end of lines or at blank lines.
306 Stay within 120 columns, unless exceeding 120 columns significantly increases readability and does not hide information.
307 (Less is acceptable. More than 140 makes it difficult to read on Github so that shall never be exceeded.)
309 Take maximum possible advantage of compile time checking, so generally warnings should be as strict as possible.
311 Don't call or reference "upwards". That is don't call or use anything in a software layer that is above the current layer. The software layers are not that obvious in Betaflight, but we can certainly say that device drivers are the bottom layer and so should not call or use anything outside the device drivers.
313 Target specific code (e.g. #ifdef CC3D) is not permissible outside of the `src/main/target` directory.
315 `typedef void handlerFunc(void);` is easier to read than `typedef void (*handlerFuncPtr)(void);`.
317 Code should be spherical.
318 That is its surface area (public interfaces) relative to its functionality should be minimised.
319 Which is another way of saying that the public interfaces shall be easy to use,
320 do something essential and all implementation should be hidden and unimportant to the user
322 Code should work in theory as well as in practice.
323 It should be based on sound mathematical, physical or computer science principles rather than just heuristics.
324 This is important for test code too. Tests shall be based on such principles and real-world properties so they don't just test the current implementation as it happens to be.
326 Guidelines not tramlines: guidelines are not totally rigid - they can be broken when there is good reason.