A programming idiom or code idiom is a syntactic fragment that recurs frequently across software projects and has a single semantic role, often expressing a special feature of a recurring construct in one or more programming languages. Developers recognize programming idioms by associating and giving meaning to one or more code fragments. The idiom can be seen as a concept underlying a pattern in code, which is represented in implementation by contiguous or scattered code fragments. These fragments are available in several programming languages, frameworks or even libraries. Generally speaking, a programming idiom is a natural language expression of a simple task, algorithm, or data structure that is not a built-in feature in the programming language being used, or, conversely, the use of an unusual or notable feature that is built into a programming language.
Knowing the idioms associated with a programming language and how to use them is an important part of gaining fluency in that language, and transferring knowledge in the form of analogies from one language or framework to another.
The adverbial or adjectival use of the term often takes the meaning of using a programming language in a typical way. For example, an idiomatic way to manage dynamic memory in C would be to use the C standard library functions malloc and free. Such code would be well intelligible to somebody familiar with C, and would be unlikely to cause issues with software portability to different computing platforms. On the other hand, if the code would forgo the use of these standard functions, and instead request memory using the system call sbrk to achieve some special behavior, that could be considered non-idiomatic; it would require more effort to understand and not be portable to non-Unix-like systems.
Examples of simple idiomsEdit
Printing Hello WorldEdit
One of the most common starting points to learn to program or notice the syntax differences between a known language and a new one.
It has several implementations, among them the code fragments for C++:
std::cout << "Hello World\n";
Inserting an element in an arrayEdit
This idiom helps developers understand how to manipulate collections in a given language, particularly inserting an element x at a position i in a list s and moving the elements to its right.
s.splice(i, 0, x);
splice(@s, $i, 0, $x)
- "Mining Idioms from Source Code. Miltiadis Allamanis, Charles A Sutton. FSE 2014: Proceedings of the 22nd ACM SIGSOFT International Symposium on Foundations of Software Engineering November 2014 Pages 472–483". arxiv.org.
- "Print Hello World". www.programming-idioms.org.
- "Insert element in list". www.programming-idioms.org.