Programming style
Encyclopedia
Programming style is a set of rules or guidelines used when writing the source code
Source code
In computer science, source code is text written using the format and syntax of the programming language that it is being written in. Such a language is specially designed to facilitate the work of computer programmers, who specify the actions to be performed by a computer mostly by writing source...

 for a computer program
Computer program
A computer program is a sequence of instructions written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute...

. It is often claimed that following a particular programming style will help programmer
Programmer
A programmer, computer programmer or coder is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software. One who practices or professes a formal approach to...

s to read and understand source code conforming to the style, and help to avoid introducing errors.

A classic work on the subject was The Elements of Programming Style, written in the 1970s, and illustrated with examples from the Fortran
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...

 and PL/I
PL/I
PL/I is a procedural, imperative computer programming language designed for scientific, engineering, business and systems programming applications...

 languages prevalent at the time.

The programming style used in a particular program may be derived from the 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...

 of a company or other computing organization, as well as the preferences of the author of the code. Programming styles are often designed for a specific programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

 (or language family): style considered good in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 source code may not be appropriate for BASIC source code, and so on. However, some rules are commonly applied to many languages.

Elements of good style

Good style is a subjective matter, and is difficult to define. However, there are several elements common to a large number of programming styles. The issues usually considered as part of programming style include the layout of the source code, including indentation; the use of white space around operators and keywords; the capitalization or otherwise of keywords and variable names; the style and spelling of user-defined identifiers, such as function, procedure and variable names; and the use and style of comments.

Code appearance

Programming styles commonly deal with the visual appearance of source code, with the goal of requiring less human cognitive effort to extract information about the program. Software has long been available that formats source code automatically, leaving coders to concentrate on naming, logic, and higher techniques. As a practical point, using a computer to format source code saves time, and it is possible to then enforce company-wide standards without debates.

Indentation

Indent style
Indent style
In computer programming, an indent style is a convention governing the indentation of blocks of code to convey the program's structure. This article largely addresses the C programming language and its descendants, but can be applied to most other programming languages...

s assist in identifying control flow and blocks of code. In some programming languages indentation is used to delimit logical blocks of code; correct indentation in these cases is more than a matter of style. In other languages indentation and whitespace do not affect function, although logical and consistent indentation makes code more readable. Compare:


if (hours < 24 && minutes < 60 && seconds < 60) {
return true;
} else {
return false;
}


or

if (hours < 24 && minutes < 60 && seconds < 60)
{
return true;
}
else
{
return false;
}

with something like


if ( hours<
24 && minutes<
60 && seconds<
60 )
{return true
} else
{return false
}


The first two examples are probably much easier to read because they are indented in an established way (a "hanging paragraph" style). This indentation style is especially useful when dealing with multiple nested constructs.

ModuLiq

The ModuLiq Zero Indent Style groups with carriage returns rather than indents. Compare all of the above to:


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

else
return false;

Python

Python uses indentation to indicate control structures, so correct indentation is required. By doing this, the need for bracketing with curly braces (i.e. { and }) is eliminated. On the other hand copying and pasting Python code can lead to problems, because the indentation level of the pasted code may not be the same as the indentation level of the current line. Such reformatting can be tedious to do by hand, but some text editor
Text editor
A text editor is a type of program used for editing plain text files.Text editors are often provided with operating systems or software development packages, and can be used to change configuration files and programming language source code....

s and IDE
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

s have features to do it automatically. There are also problems when Python code could be rendered unusable when posted on a forum or web page that removes whitespace, though this problem can be avoided where it is possible to enclose code in whitespace-preserving tags such as "<pre> ... </pre>" (for HTML
HTML
HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....

), "[code]" ... "[/code]" (for bbcode
BBCode
BBCode or Bulletin Board Code is a lightweight markup language used to format posts in many message boards. The available tags are usually indicated by square brackets surrounding a keyword, and they are parsed by the message board system before being translated into a markup language that web...

), etc.

Haskell

Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

 similarly has the off-side rule
Off-side rule
A computer programming language is said to adhere to the off-side rule if the scope of declarations in that language is expressed by their indentation. The term and the idea are attributed to Peter J. Landin, and the term can be seen as a pun on the offside law of football .- Definition :Peter J...

 which lets indentation define blocks; however, unlike in Python, indentation is not compulsory in Haskell — curly braces and semicolons can be (and occasionally are) used instead.

Vertical alignment

It is often helpful to align similar elements vertically, to make typo-generated bugs more obvious. Compare:

$search = array('a', 'b', 'c', 'd', 'e');
$replacement = array('foo', 'bar', 'baz', 'quux');

// Another example:

$value = 0;
$anothervalue = 1;
$yetanothervalue = 2;

with:

$search = array('a', 'b', 'c', 'd', 'e');
$replacement = array('foo', 'bar', 'baz', 'quux');

// Another example:

$value = 0;
$anothervalue = 1;
$yetanothervalue = 2;


The latter example makes two things intuitively clear that were not clear in the former:
  • the search and replace terms are related and match up: they are not discrete variables;
  • there is one more search term than there are replacement terms. If this is a bug, it is now more likely to be spotted.


Arguments against vertical alignment are
  • Inter-line false dependencies; tabular formatting creates dependencies across lines. For example, if an identifier with a long name is added to a tabular layout, the column width may have to be increased to accommodate it. This forces a bigger change to the source code than necessary, and the essential change may be lost in the noise. This is detrimental to source code control where inspecting differences between versions is essential.

  • Brittleness; if a programmer does not neatly format the table when making a change; maybe legitimately with the previous point in mind; the result becomes a mess that deteriorates with further such changes.

  • Resistance to change; tabular formatting requires more effort to maintain. This may put off a programmer from making a beneficial change, such as adding, correcting or improving the name of an identifier, because it will mess up the formatting.

  • Reliance on mono-spaced font; tabular formatting assumes that the editor uses a fixed-width font. Most modern code editors support proportional fonts, and the programmer may prefer to use a proportional font for readability.

  • Tool dependence; some of the effort of maintaining alignment can be alleviated by tools (e.g. a source code editor
    Source code editor
    A source code editor is a text editor program designed specifically for editing source code of computer programs by programmers. It may be a standalone application or it may be built into an integrated development environment ....

     that supports elastic tabstop
    Elastic tabstop
    In text editor applications in computing, elastic tabstops are an alternative way to handle tabstops, with a primary focus on editing source code in computer programming. The idea was first proposed by Nick Gravgaard as a solution for programmers who argue about what kind of indentation is best;...

    s), although that creates a reliance on tools.

Spaces

In those situations where some whitespace
Whitespace (computer science)
In computer science, whitespace is any single character or series of characters that represents horizontal or vertical space in typography. When rendered, a whitespace character does not correspond to a visual mark, but typically does occupy an area on a page...

 is required the grammars of most free-format languages are unconcerned with the amount that appears. Style related to whitespace is commonly used to enhance readability
Readability
Readability is the ease in which text can be read and understood. Various factors to measure readability have been used, such as "speed of perception," "perceptibility at a distance," "perceptibility in peripheral vision," "visibility," "the reflex blink technique," "rate of work" , "eye...

. There are currently no known hard facts (conclusions from studies) about which of the whitespace styles are having the best readability.

For instance, compare the following syntactically equivalent examples of C code.


int i;
for(i=0;i<10;++i){
printf("%d",i*i+i);
}

versus

int i;
for (i=0; i<10; ++i) {
printf("%d", i*i+i);
}

versus

int i;
for (i = 0; i < 10; ++i) {
printf("%d", i * i + i);
}

versus

int i;
for( i = 0; i < 10; ++i ) {
printf( "%d", i * i + i );
}

Tabs

The use of tabs
Tab key
Tab key on a keyboard is used to advance the cursor to the next tab stop.- Origin :The word tab derives from the word tabulate, which means "to arrange data in a tabular, or table, form"...

 to create white space presents particular issues when not enough care is taken because the location of the tabulation point can be different depending on the tools being used and even the preferences of the user.

As an example, one programmer prefers tab stop
Tab stop
A tab stop on a typewriter is a location where the carriage movement is halted by mechanical gears. Tab stops are set manually, and pressing the tab key causes the carriage to go to the next tab stop...

s of four and has his toolset configured this way, and uses these to format his code.


int ix; // Index to scan array
long sum; // Accumulator for sum


Another programmer prefers tab stops of eight, and his toolset is configured this way. When he examines his code, he may well find it difficult to read.


int ix; // Index to scan array
long sum; // Accumulator for sum


One widely used solution to this issue may involve forbidding the use of tabs for alignment or rules on how tab stops must be set. Note that tabs work fine provided they are used consistently, restricted to logical indentation, and not used for alignment:


class MyClass {
int foobar(int qux, // first parameter
int quux); // second parameter
int foobar2(int qux, // first parameter
int quux, // second parameter
int quuux); // third parameter
};

See also

  • 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...

  • Indent style
    Indent style
    In computer programming, an indent style is a convention governing the indentation of blocks of code to convey the program's structure. This article largely addresses the C programming language and its descendants, but can be applied to most other programming languages...

  • MISRA C
    MISRA C
    MISRA C is a software development standard for the C programming language developed by MISRA . Its aims are to facilitate code safety, portability and reliability in the context of embedded systems, specifically those systems programmed in ISO C...

  • Naming convention (programming)
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK