Coding conventions

Coding conventions

Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices and methods for each aspect of a piece program written in this language. These conventions usually cover file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices, programming principles, programming rules of thumb, etc. Software programmers are highly recommended to follow these guidelines to help improve the readability of their source code and make software maintenance easier. Coding conventions are only applicable to the human maintainers and peer reviewers of a software project. Conventions may be formalized in a documented set of rules that an entire team or company follows, or may be as informal as the habitual coding practices of an individual. Coding conventions are not enforced by compilers. As a result, not following some or all of the rules has no impact on the executable programs created from the source code.

Contents

Software maintenance

Reducing the cost of software maintenance is the most often cited reason for following coding conventions. In their introduction to code conventions for the Java Programming Language, Sun Microsystems provides the following rationale:[1]

Code conventions are important to programmers for a number of reasons:

  • 80% of the lifetime cost of a piece of software goes to maintenance.[citation needed]
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
  • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

Quality

Software peer review frequently involves reading source code. This type of peer review is primarily a defect detection activity. By definition, only the original author of a piece of code has read the source file before the code is submitted for review. Code that is written using consistent guidelines is easier for other reviewers to understand and assimilate, improving the efficacy of the defect detection process.

Even for the original author, consistently coded software eases maintainability. There is no guarantee that an individual will remember the precise rationale for why a particular piece of code was written in a certain way long after the code was originally written. Coding conventions can help. Consistent use of whitespace improves readability and reduces the time it takes to understand the software.

Refactoring

Refactoring refers to a software maintenance activity where source code is modified to improve readability or improve its structure. Software is often refactored to bring it into conformance with a team's stated coding standards after its initial release. Any change that does not alter the behavior of the software can be considered refactoring. Common refactoring activities are changing variable names, renaming methods, moving methods or whole classes and breaking large methods (or functions) into smaller ones.

Agile software development methodologies plan for regular (or even continuous) refactoring making it an integral part of the team software development process.[2]

Task automation

Coding conventions allow to have simple scripts or programs whose job is to process source code for some purpose other than compiling it into an executable. It is common practice to count the software size (Source lines of code) to track current project progress or establish a baseline for future project estimates.

Consistent coding standards can, in turn, make the measurements more consistent. Special tags within source code comments are often used to process documentation, two notable examples are javadoc and doxygen. The tools specifies the use of a set of tags, but their use within a project is determined by convention.

Coding conventions simplify writing new software whose job is to process existing software. Use of static code analysis has grown consistently since the 1950s. Some of the growth of this class of development tools stems from increased maturity and sophistication of the practitioners themselves (and the modern focus on safety and security), but also from the nature of the languages themselves.

Language factors

All software practitioners must grapple with the problems of organizing and managing very many detailed instructions, each of which will eventually be processed in order to perform the task for which it was written. For all but the smallest software projects, source code (instructions) are partitioned into separate files and frequently among many directories. It was natural for programmers to collect closely related functions (behaviors) in the same file and to collect related files into directories. As software development evolved from purely procedural programming (such as found in FORTRAN) towards more object-oriented constructs (such as found in C++), it became the practice to write the code for a single (public) class in a single file (the 'one class per file' convention).[3][4] Java has gone one step further - the Java compiler returns an error if it finds more than one public class per file.

A convention in one language may be a requirement in another. Language conventions also affect individual source files. Each compiler (or interpreter) used to process source code is unique. The rules a compiler applies to the source creates implicit standards. For example, Python code is much more consistently indented than, say Perl, because whitespace (indentation) is actually significant to the interpreter. Python does not use the brace syntax Perl uses to delimit functions. Changes in indentation serve as the delimiters.[5][6] Tcl, which uses a brace syntax similar to Perl or C/C++ to delimit functions, does not allow the following, which seems fairly reasonable to a C programmer:

set i 0
while {$i < 10} 
{
   puts "$i squared = [expr $i*$i]"
   incr i
}

The reason is that in Tcl, curly braces are not used only to delimit functions as in C or Java. More generally, curly braces are used to group words together into a single argument.[7][8] In Tcl, the word while takes two arguments, a condition and an action. In the example above, while is missing its second argument, its action (because the Tcl also uses the newline character to delimit the end of a command).

Common conventions

As mentioned above, common coding conventions may cover the following areas:

Examples

Only one statement should occur per line

For example, in Java this would involve having statements written like this:

++a;
b = a;

But not like this:

++a; b = a;

Boolean values in decision structures

Some programmers suggest that coding where the result of a decision is merely the computation of a Boolean value, are overly verbose and error prone. They prefer to have the decision in the computation itself, like this:

return (hours < 24) && (minutes < 60) && (seconds < 60);

The difference is entirely stylistic, because optimizing compilers may produce identical object code for both forms. However, stylistically, programmers disagree which form is easier to read and maintain.

Arguments in favor of the longer form include: it is then possible to set a per-line breakpoint on one branch of the decision; further lines of code could be added to one branch without refactoring the return line, which would increase the chances of bugs being introduced; the longer form would always permit a debugger to step to a line where the variables involved are still in scope.

Left-hand comparisons

In languages which use one symbol (typically a single equals sign, (=)) for assignment and another (typically two equals signs, (==) for comparison (e.g. C/C++, Java, ActionScript 3, PHP, Perl numeric context, and most languages in the last 15 years), and where assignments may be made within control structures, there is an advantage to adopting the left-hand comparison style: to place constants or expressions to the left in any comparison. [9] [10]


Here are both left and right-hand comparison styles, applied to a line of Perl code. In both cases, this compares the value in the variable $a against 42, and if it matches, executes the code in the subsequent block.

if ($a == 42) { ... }  # A right-hand comparison checking if $a equals 42.
if (42 == $a) { ... }  # Recast, using the left-hand comparison style.

The difference occurs when a developer accidentally types = instead of ==:

if ($a = 42) { ... }  # Inadvertent assignment which is often hard to debug
if (42 = $a) { ... }  # Compile time error indicates source of problem

The first (right-hand) line now contains a potentially subtle flaw: rather than the previous behaviour, it now sets the value of $a to be 42, and then always runs the code in the following block. As this is syntactically legitimate, the error may go unnoticed by the programmer, and the software may ship with a bug.

The second (left-hand) line contains a semantic error, as numeric values cannot be assigned to. This will result in a diagnostic message being generated when the code is compiled, so the error cannot go unnoticed by the programmer.

Some languages have built-in protections against inadvertent assignment. Java and C#, for example, do not support automatic conversion to boolean for just this reason.

The risk can also be mitigated by use of static code analysis tools that can detect this issue.

Looping and control structures

The use of logical control structures for looping adds to good programming style as well. It helps someone reading code to better understand the program's sequence of execution (in imperative programming languages). For example, in pseudocode:

i = 0
 
while i < 5
  print i * 2
  i = i + 1
end while
 
print "Ended loop"

The above snippet obeys the naming and indentation style guidelines, but the following use of the "for" construct may be considered easier to read:

for i = 0, i < 5, i=i+1
  print i * 2
 
print "Ended loop"

In many languages, the often used "for each element in a range" pattern can be shortened to:

for i = 0 to 5
  print i * 2
 
print "Ended loop"

In programming languages that allow curly brackets, it has become common for style documents to require that even where optional, curly brackets be used with all control flow constructs.

for (i = 0 to 5) {
  print i * 2;
}
 
print "Ended loop";

This prevents program-flow bugs which can be time-consuming to track down, such as where a terminating semicolon is introduced at the end of the construct (a common typo):

 for (i = 0; i < 5; ++i);
    printf("%d\n", i*2);    /* The incorrect indentation hides the fact 
                               that this line is not part of the loop body. */
 
 printf("Ended loop");

...or where another line is added before the first:

 for (i = 0; i < 5; ++i)
    fprintf(logfile, "loop reached %d\n", i);
    printf("%d\n", i*2);    /* The incorrect indentation hides the fact 
                               that this line is not part of the loop body. */
 
 printf("Ended loop");

Lists

Where items in a list are placed on separate lines, it is sometimes considered good practice to add the item-separator after the final item, as well as between each item, at least in those languages where doing so is supported by the syntax (e.g., C, Java)

const char *array[] = {
    "item1",
    "item2",
    "item3",  /* still has the comma after it */
};

This prevents syntax errors or subtle string-concatenation bugs when the list items are re-ordered or more items are added to the end, without the programmer's noticing the "missing" separator on the line which was previously last in the list. However, this technique can result in a syntax error (or misleading semantics) in some languages. Even for languages that do support trailing commas, not all list-like syntactical constructs in those languages may support it.

See also

References

  1. ^ "Code Conventions for the Java Programming Language : Why Have Code Conventions". Sun Microsystems, Inc.. 1999-04-20. http://java.sun.com/docs/codeconv/html/CodeConventions.doc.html#16712. 
  2. ^ Jeffries, Ron (2001-11-08). "What is Extreme Programming? : Design Improvement". XP Magazine. http://www.xprogramming.com/xpmag/whatisxp.htm#design. 
  3. ^ Hoff, Todd (2007-01-09). "C++ Coding Standard : Naming Class Files". http://www.possibility.com/Cpp/CppCodingStandard.html#cflayout. 
  4. ^ FIFE coding standards
  5. ^ van Rossum, Guido; Fred L. Drake, Jr., editor (2006-09-19). "Python Tutorial : First Steps Towards Programming". Python Software Foundation. http://docs.python.org/tut/node5.html#SECTION005200000000000000000. 
  6. ^ Raymond, Eric (2000-05-01). "Why Python?". Linux Journal. http://www.linuxjournal.com/article/3882. 
  7. ^ Tcl Developer Xchange. "Summary of Tcl language syntax". ActiveState. http://www.tcl.tk/man/tcl8.4/TclCmd/Tcl.htm. 
  8. ^ Staplin, George Peter (2006-07-16). "Why can I not start a new line before a brace group". 'the Tcler's Wiki'. http://wiki.tcl.tk/8344. 
  9. ^ Sklar, David; Adam Trachtenberg (2003). PHP Cookbook. O'Reilly. , recipe 5.1 "Avoiding == Versus = Confusion", p118
  10. ^ "C Programming FAQs: Frequently Asked Questions". Addison-Wesley, 1995. Nov. 2010. http://c-faq.com/style/revtest.html. 

External links

Coding conventions for languages

Coding conventions for projects


Wikimedia Foundation. 2010.

Игры ⚽ Поможем сделать НИР

Look at other dictionaries:

  • Coding Convention — Als Programmierstil (engl. code conventions, coding conventions, coding standards) bezeichnet man einen Satz von Regeln, denen sich der Programmierer unterwirft. Üblicherweise werden hierunter Regeln verstanden, nach denen der Quelltext einer… …   Deutsch Wikipedia

  • Coding Style — Als Programmierstil (engl. code conventions, coding conventions, coding standards) bezeichnet man einen Satz von Regeln, denen sich der Programmierer unterwirft. Üblicherweise werden hierunter Regeln verstanden, nach denen der Quelltext einer… …   Deutsch Wikipedia

  • Coding standards — Als Programmierstil (engl. code conventions, coding conventions, coding standards) bezeichnet man einen Satz von Regeln, denen sich der Programmierer unterwirft. Üblicherweise werden hierunter Regeln verstanden, nach denen der Quelltext einer… …   Deutsch Wikipedia

  • Naming conventions (programming) — In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers in source code and documentation. Reasons for using a naming convention (as opposed to allowing programmers to choose… …   Wikipedia

  • Best Coding Practices — for software development can be broken into many levels based on the coding language, the platform, the target environment and so forth. Using best practices for a given situation greatly reduces the probability of introducing errors into your… …   Wikipedia

  • modified key coding system —   n.    a modification of the standard key coding system, in which the TMK of a system with three or more levels of keying has a single letter name, and keys at lower levels are named following SKCS conventions …   Locksmith dictionary

  • Naming convention (programming) — In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc. in source code and documentation. Reasons for using a naming convention …   Wikipedia

  • Programmierstil — Ein Programmierstil (engl. code conventions, coding conventions, coding standards) ist ein Satz von Regeln, denen sich der Programmierer unterwirft. Üblicherweise werden hierunter Regeln verstanden, nach denen der Quelltext in einer… …   Deutsch Wikipedia

  • Code Convention — Als Programmierstil (engl. code conventions, coding conventions, coding standards) bezeichnet man einen Satz von Regeln, denen sich der Programmierer unterwirft. Üblicherweise werden hierunter Regeln verstanden, nach denen der Quelltext einer… …   Deutsch Wikipedia

  • Indent Style — Als Einrückungsstil (engl. indent style) wird die Art und Weise bezeichnet, Quelltext von Programmen zwecks Lesbarkeit einzurücken und umschließende Syntax Elemente wie geschweifte Klammern {} zu positionieren. Als alternativer Name ist daher… …   Deutsch Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”