This chapter describes the source code style preferred by the LinuxCNC team.
1. Do no harm
When making small edits to code in a style different than the one described below, observe the local coding style. Rapid changes from one coding style to another decrease code readability.
Never check in code after running "indent" on it. The whitespace changes introduced by indent make it more difficult to follow the revision history of the file.
No use un editor que realice cambios innecesarios en los espacios en blanco (por ejemplo, que reemplace 8 espacios con un tabulador en una línea no modificada, o ajuste de texto en líneas que no han sido modificadas).
2. Tab Stops
A tab stop always corresponds to 8 spaces. Do not write code that displays correctly only with a differing tab stop setting.
3. Indentation
Use 4 spaces per level of indentation. Combining 8 spaces into one tab is acceptable but not required.
4. Placing Braces
Put the opening brace last on the line, and put the closing brace first:
if (x) { // do something appropriate }
The closing brace is on a line of its own, except in the cases where it is followed by a continuation of the same statement, i.e. a while in a do-statement or an else in an if-statement, like this:
do { // something important } while (x > 0);
and
if (x == y) { // do one thing } else if (x < y) { // do another thing } else { // do a third thing }
This brace-placement also minimizes the number of empty (or almost empty) lines, which allows a greater amount of code or comments to be visible at once in a terminal of a fixed size.
5. Naming
C is a Spartan language, and so should your naming be. Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like ThisVariableIsATemporaryCounter. A C programmer would call that variable tmp, which is much easier to write, and not the least more difficult to understand.
However, descriptive names for global variables are a must. To call a global function foo is a shooting offense.
GLOBAL variables (to be used only if you really need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that count_active_users() or similar, you should not call it cntusr().
Codificar el tipo de una función en el nombre (llamada notación húngara) no tiene sentido; el compilador conoce los tipos de todos modos y puede verificarlos, y solo confunde al programador. No es de extrañar que Microsoft haga programas con errores.
LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called i. Calling it loop_counter is non-productive, if there is no chance of it being misunderstood. Similarly, tmp can be just about any type of variable that is used to hold a temporary value.
Si tiene miedo de mezclar sus nombres de variables locales, tiene otro problema, que se llama síndrome de desequilibrio de la hormona del crecimiento funcional. Ver el siguiente capítulo.
6. Functions
Las funciones deben ser cortas y fáciles, y hacer una sola cosa. Deben caber en una o dos pantallas de texto (el tamaño de pantalla ISO/ANSI es 80x24, como todos sabemos), hacer una cosa y hacerla bien.
The maximum length of a function is inversely proportional to the complexity and indentation level of that function. So, if you have a conceptually simple function that is just one long (but simple) case-statement, where you have to do lots of small things for a lot of different cases, it’s OK to have a longer function.
However, if you have a complex function, and you suspect that a less-than-gifted first-year high-school student might not even understand what the function is all about, you should adhere to the maximum limits all the more closely. Use helper functions with descriptive names (you can ask the compiler to in-line them if you think it’s performance-critical, and it will probably do a better job of it that you would have done).
Otra medida de la función es el número de variables locales. No deben exceder de 5-10, o algo estás haciendo mal. Repensar la función, y dividirla en pedazos más pequeños. Un cerebro humano generalmente puede realizar un seguimiento de aproximadamente 7 cosas diferentes, cualquier cosa más y se confunde. Sabes que eres brillante, pero tal vez te gustaría entender lo que hiciste dentro de 2 semanas.
7. Commenting
Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it’s much better to write the code so that the working is obvious, and it’s a waste of time to explain badly written code.
Generally, you want your comments to tell WHAT your code does, not HOW. A boxed comment describing the function, return value, and who calls it placed above the body is good. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably re-read the Functions section again. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does it.
If comments along the lines of /* Fix me */ are used, please, please, say why something needs fixing. When a change has been made to the affected portion of code, either remove the comment, or amend it to indicate a change has been made and needs testing.
8. Shell Scripts & Makefiles
Not everyone has the same tools and packages installed. Some people use vi, others emacs - A few even avoid having either package installed, preferring a lightweight text editor such as nano or the one built in to Midnight Commander.
gawk versus mawk - Again, not everyone will have gawk installed, mawk is nearly a tenth of the size and yet conforms to the POSIX AWK standard. If some obscure gawk specific command is needed that mawk does not provide, than the script will break for some users. The same would apply to mawk. In short, use the generic awk invocation in preference to gawk or mawk.
9. C++ Conventions
Los estilos de codificación de C++ siempre terminan en acalorados debates (un poco como los argumentos de emacs versus vi). Una cosa es cierta, sin embargo; el estilo común utilizado por todos los que trabajan en un proyecto conduce a la uniformidad y a código legible.
Convenciones de nomenclatura: las constantes #define o enumeraciones debe estar en mayúscula. Justificación: hace que sea más fácil detectar constantes de tiempo de compilación en el código fuente, p.ej. EMC_MESSAGE_TYPE.
Las clases y los espacios de nombres deben poner en mayúscula la primera letra de cada palabra y evitar guiones bajos. Justificación: identifica clases, constructores y destructores, p.ej. GtkWidget.
Los métodos (o nombres de funciones) deben seguir las recomendaciones C anteriores y no debe incluir el nombre de la clase. Justificación: mantiene un estilo común en fuentes C y C++, p.ej. get_foo_bar().
Sin embargo, los métodos booleanos son más fáciles de leer si se evitan los guiones bajos y usan un prefijo is (no debe confundirse con los métodos que manipulan un booleano). Justificación: identifica el valor de retorno como VERDADERO o FALSO y nada más, p.ej. isOpen, isHomed.
Do NOT use Not in a boolean name, it leads only leads to confusion when doing logical tests, e.g., isNotOnLimit or is_not_on_limit are BAD.
Los nombres de las variables deben evitar el uso de mayúsculas y guiones bajos a excepción de nombres locales o privados. El uso de variables globales debería evitarse tanto como sea posible. Justificación: aclara cuáles son variables y cuales son métodos. Ej. Público: axislimit. Ej. Privado: maxvelocity_ .
9.1. Specific method naming conventions
Los términos get y set deben usarse donde se accede a un atributo directamente. Justificación: indica el propósito de la función o método, p.ej. get_foo set_bar.
For methods involving boolean attributes, set & reset is preferred. Rationale: As above. e.g. set_amp_enable reset_amp_fault
Math intensive methods should use compute as a prefix. Rationale: Shows that it is computationally intensive and will hog the CPU. e.g. compute_PID
Abbreviations in names should be avoided where possible - The exception is for local variable names. Rationale: Clarity of code. e.g. pointer is preferred over ptr compute is preferred over cmp compare is again preferred over cmp.
Las enumeraciones y otras constantes pueden tener como prefijo un nombre de tipo común p.ej. enum COLOR{COLOR_RED, COLOR_BLUE};.
Se debe evitar el uso excesivo de macros y defines. Se prefieren métodos o funciones. Justificación: mejora el proceso de depuración.
Include Statements Header files must be included at the top of a source file and not scattered throughout the body. They should be sorted and grouped by their hierarchical position within the system with the low level files included first. Include file paths should NEVER be absolute - Use the compiler -I flag instead to extend the search path. Rationale: Headers may not be in the same place on all systems.
Los punteros y las referencias deben tener su símbolo de referencia junto al nombre de la variable y no junto al nombre del tipo. Justificación: Reduce la confusión, p.ej. float *x o int &i.
Las pruebas implícitas para cero no deben usarse excepto para variables booleanas, p.ej. if (spindle_speed != 0) NO if (spindle_speed).
Solo las declaraciones de control de bucle deben incluirse en una construcción for(). p.ej. sum = 0; for (i = 0; i < 10; i++) { sum += value[i]; }
NO: for (i=0,sum=0; i<10; i++) sum += value[I];.
Del mismo modo, deben evitarse las declaraciones ejecutables en condicionales. p.ej. if (fd = open(nombre_archivo) es malo.
Complex conditional statements should be avoided - Introduce temporary boolean variables instead.
Los paréntesis deben usarse en abundancia en las expresiones matemáticas. - No confíe en la precedencia del operador cuando un paréntesis adicional aclararía las cosas.
File names: C++ sources and headers use .cc and .hh extension. The use of .c and .h are reserved for plain C. Headers are for class, method, and structure declarations, not code (unless the functions are declared inline).
10. Python coding standards
Utilice el estilo PEP 8 para Código de Python.
11. Comp coding standards
In the declaration portion of a .comp file, begin each declaration at the first column. Insert extra blank lines when they help group related items.
In the code portion of a .comp file, follow normal C coding style.