Programming idiom

A programming idiom is a means of expressing a recurring construct in one or more programming languages. Generally speaking, a programming idiom is an 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. The term can be used more broadly, however, to refer to complex algorithms or programming design patterns.

Knowing the idioms associated with a programming language and how to use them is an important part of gaining fluency in that language.

Examples of simple idioms

Set as associative array

In languages that do not support the set data type, but do support associative arrays, a set can be implemented as an associative array where the value is either irrelevant or is the unit type (or a sentinel value like 1).

This is useful for example if one needs to perform an operation in which we often need to determine whether some arbitrary value is in a given list or array or not. Set membership in a list or (unsorted) array is an O(n) operation, as one needs to scan the list until the element is found or the end is reached. By contrast, lookup or membership in an associative array is frequently O(1), for example if it is implemented as a hash table.

The following idiom is commonly used to express this in Perl, which has fast associative arrays (implemented as hash tables), but no sets:

  my %elements = map { $_ => 1 } @elements;

Pimpl idiom

In object-oriented programming the implementation details of an API-level class can be hidden in an own implementation class. An opaque pointer (or reference) to that class is stored in the API-level class.

See also

External links

This article is issued from Wikipedia - version of the 10/13/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.