HOME

TheInfoList



OR:

Programming style, also known as code style, is a set of rules or guidelines used when writing the
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
for a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to execute. Computer programs are one component of software, which also includes documentation and other intangible components. A computer program ...
. It is often claimed that following a particular programming style will help
programmer A computer programmer, sometimes referred to as a software developer, a software engineer, a programmer or a coder, is a person who creates computer programs — often for larger computer software. A programmer is someone who writes/creates ...
s 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 ''The Elements of Programming Style'', by Brian W. Kernighan and P. J. Plauger, is a study of programming style, advocating the notion that computer programs should be written not only to satisfy the compiler or personal programming "style", bu ...
'', written in the 1970s, and illustrated with examples from the Fortran and
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
languages prevalent at the time. The programming style used in a particular program may be derived from the
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 program written in that language. These conventions usually cover file organization, inde ...
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 A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
(or language family): style considered good in C source code may not be appropriate for
BASIC BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
source code, etc. 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 Layout may refer to: * Page layout, the arrangement of visual elements on a page ** Comprehensive layout (comp), a proposed page layout presented by a designer to their client * Layout (computing), the process of calculating the position of obje ...
of the source code, including
indentation __FORCETOC__ In the written form of many languages, an indentation or indent is an empty space at the beginning of a line to signal the start of a new paragraph. Many computer languages have adopted this technique to designate "paragraphs" or ot ...
; 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 readability. 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 Debate is a process that involves formal discourse on a particular topic, often including a moderator and audience. In a debate, arguments are put forward for often opposing viewpoints. Debates have historically occurred in public meetings, a ...
.


Indentation

Indentation style In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be (and often ...
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 white space do not affect function, although logical and consistent indentation makes code more readable. Compare: if (hours < 24 && minutes < 60 && seconds < 60) else or if (hours < 24 && minutes < 60 && seconds < 60) else with something like if ( hours < 24 && minutes < 60 && seconds < 60 ) else 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 Indentation Style groups with carriage returns rather than indentations. Compare all of the above to: if (hours < 24 && minutes < 60 && seconds < 60) return true; else return false;


Lua

Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
does not use the traditional
curly braces A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
or
parenthesis A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
. if/else statements only require the expression be followed by then, and closing the if/else statement with end. if hours < 24 and minutes < 60 and seconds < 60 then return true else return false end Indentation is optional. and, or, not are used in between true/false statements. They are true/false statements, as print(not true) would mean false.


Python

Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
uses indentation to indicate control structures, so ''correct indentation'' is required. By doing this, the need for bracketing with
curly braces A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
(i.e. ) 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 A text editor is a type of computer program that edits plain text. Such programs are sometimes known as "notepad" software (e.g. Windows Notepad). Text editors are provided with operating systems and software development packages, and can be us ...
s and IDEs have features to do it automatically. There are also problems when Python code being rendered unusable when posted on a forum or web page that removes white space, though this problem can be avoided where it is possible to enclose code in white space-preserving tags such as "<pre> ... </pre>" (for
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScri ...
), "
ode An ode (from grc, ᾠδή, ōdḗ) is a type of lyric poetry. Odes are elaborately structured poems praising or glorifying an event or individual, describing nature intellectually as well as emotionally. A classic ode is structured in three majo ...
... "
code In communications and information processing, code is a system of rules to convert information—such as a letter, word, sound, image, or gesture—into another form, sometimes shortened or secret, for communication through a communication ...
(for
bbcode BBCode ("Bulletin Board Code") is a lightweight markup language used to format messages in much Internet forum software, first introduced in 1998. The available "tags" of BBCode are usually indicated by square brackets ( _and_.html" ;"title="/code> ...
), etc. if hours < 24 and minutes < 60 and seconds < 60: return True else: return False Notice that Python does not use curly braces, but a regular colon (e.g. else:). Many Python programmers tend to follow a commonly agreed style guide known as PEP8. There are tools designed to automate PEP8 compliance.


Haskell

Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
similarly has the
off-side rule A computer programming language is said to adhere to the off-side rule of syntax if blocks in that language are expressed by their indentation. The term was coined by Peter Landin, possibly as a pun on the offside rule in association football. ...
, i.e. it has a two-dimension syntax where indentation is meaningful to define blocks (although, an alternate syntax uses curly braces and semicolons). Haskell is a declarative language, there are statements, but declarations within a Haskell script. Example: let c_1 = 1 c_2 = 2 in f x y = c_1 * x + c_2 * y may be written in one line as: let in f x y = c_1 * x + c_2 * y Haskell encourage the use of
literate programming Literate programming is a programming paradigm introduced in 1984 by Donald Knuth in which a computer program is given as an explanation of its logic in a natural language, such as English, interspersed (embedded) with snippets of macros and t ...
, where extended text explain the genesis of the code. In literate Haskell scripts (named with the lhs extension), everything is a comment except blocks marked as code. The program can be written in
LaTeX Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latexes are found in nature, but synthetic latexes are common as well. In nature, latex is found as a milky fluid found in 10% of all flowering plants (angiosperms ...
, in such case the code environment marks what is code. Also each active code paragraph can be marked by preceding and ending it with an empty line, and starting each line of code with a greater than sign and a space. Here an example using LaTeX markup: The function \verb+isValidDate+ test if date is valid \begin isValidDate :: Date -> Bool isValidDate date = hh>=0 && mm>=0 && ss>=0 && hh<24 && mm<60 && ss<60 where (hh,mm,ss) = fromDate date \end observe that in this case the overloaded function is \verb+fromDate :: Date -> (Int,Int,Int)+. And an example using plain text: The function isValidDate test if date is valid > isValidDate :: Date -> Bool > isValidDate date = hh>=0 && mm>=0 && ss>=0 > && hh<24 && mm<60 && ss<60 > where (hh,mm,ss) = fromDate date observe that in this case the overloaded function is fromDate :: Date -> (Int,Int,Int).


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. However, note that there are arguments ''against'' vertical alignment: * 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
Revision control In software engineering, version control (also known as revision control, source control, or source code management) is a class of systems responsible for managing changes to computer programs, documents, large web sites, or other collections o ...
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. Simple refactoring operations, such as search-and-replace, may also break the formatting. * Resistance to modification; 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. Many 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 A source-code editor is a text editor program designed specifically for editing source code of computer programs. It may be a standalone application or it may be built into an integrated development environment (IDE) or web browser. Source-code ed ...
that supports
elastic tabstop A tab stop on a typewriter is a location where the carriage movement is halted by an adjustable end stop. Tab stops are set manually, and pressing the tab key causes the carriage to go to the next tab stop. In text editors on a computer, the sam ...
s), although that creates a reliance on such tools. For example, if a simple refactoring operation is performed on the code above, renaming variables "$replacement" to "$r" and "$anothervalue" to "$a", the resulting code will look like this: $search = array('a', 'b', 'c', 'd', 'e'); $r = array('foo', 'bar', 'baz', 'quux'); // Another example: $value = 0; $a = 1; $yetanothervalue = 2; The original sequential formatting will still look fine after such change: $search = array('a', 'b', 'c', 'd', 'e'); $r = array('foo', 'bar', 'baz', 'quux'); // Another example: $value = 0; $a = 1; $yetanothervalue = 2;


Spaces

In those situations where some white space is required, the grammars of most
free-format language In computer programming, a free-form language is a programming language in which the positioning of character (computing), characters on the page in program text is insignificant. Program text does not need to be placed in specific columns as on ...
s are unconcerned with the amount that appears. Style related to white space is commonly used to enhance
readability Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax) and its presentation (such as typographic aspects that a ...
. There are currently no known hard facts (conclusions from studies) about which of the whitespace styles have the best readability. For instance, compare the following syntactically equivalent examples of C code: int i; for(i=0;i<10;++i) versus int i; for (i = 0; i < 10; ++i)


Tabs

The use of tabs 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 A tab stop on a typewriter is a location where the carriage movement is halted by an adjustable end stop. Tab stops are set manually, and pressing the tab key causes the carriage to go to the next tab stop. In text editors on a computer, the sam ...
s of four and has their toolset configured this way, and uses these to format their code. int ix; // Index to scan array long sum; // Accumulator for sum Another programmer prefers tab stops of eight, and their toolset is configured this way. When someone else examines the original person's code, they 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 ;


See also

*
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 program written in that language. These conventions usually cover file organization, inde ...
*
MISRA C MISRA C is a set of software development guidelines for the C programming language developed by The MISRA Consortium. Its aims are to facilitate code safety, security, portability and reliability in the context of embedded systems, specifically ...
*
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, functions, and other entities in source code and documentation. Reasons for using a na ...


References


External links

*{{dmoz, /Computers/Programming/Development_Tools/Source_Code_Formatters/, Source Code Formatters Source code Articles with example C code Articles with example PHP code Articles with example pseudocode