[go: nahoru, domu]

Jump to content

Programming idiom: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Ripounet (talk | contribs)
Link to programming-idioms.org
ce
 
(100 intermediate revisions by 34 users not shown)
Line 1: Line 1:
{{short description|Group of code fragments sharing an equivalent semantic role}}
A '''programming idiom''' is a means of expressing a recurring construct in one or more [[programming language]]s. 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 pattern]]s.


In [[computer programming]], a '''programming idiom''' or '''code idiom''' is a group of [[Source code|code]] fragments sharing an equivalent [[Semantics (computer science)|semantic role]],<ref>{{cite book|title=Proceedings of the 22nd ACM SIGSOFT International Symposium on Foundations of Software Engineering|chapter=Mining idioms from source code |year=2014 |doi=10.1145/2635868.2635901 |arxiv=1404.0417 |last1=Allamanis |first1=Miltiadis |last2=Sutton |first2=Charles |pages=472–483 |isbn=9781450330565 |s2cid=2923536 }}</ref> which recurs frequently across [[software]] projects often expressing a special feature of a recurring [[Language construct|construct]] in one or more [[programming language]]s or [[Library (computing)|libraries]]. This definition is rooted in the definition of "[[idiom]]" as used in the field of linguistics. [[Software developer|Developers]] recognize programming idioms by associating meaning (semantic role) to one or more syntactical expressions within [[code snippet]]s (code fragments). The idiom can be seen as an action on a programming 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, [[software framework|framework]]s or even libraries. Generally speaking, a programming idiom's semantic role is a natural language expression of a simple task, [[algorithm]], or [[data structure]] that is not a [[built-in type|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.


Knowing the idioms associated with a programming language and how to use them is an important part of gaining [[fluency]] in that language. It also helps to transfer knowledge in the form of analogies from one language or framework to another. Such idiomatic knowledge is widely used in crowdsourced repositories to help developers overcome programming barriers.<ref>{{cite book|chapter-url=https://cs.gmu.edu/~tlatoza/papers/BarriersInFrontendWebDevelopment.pdf|title= 2022 IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC)|year=2022 |doi=10.1109/VL/HCC53370.2022.9833127 |last1=Samudio |first1=David I. |last2=Latoza |first2=Thomas D. |chapter= Barriers in Front-End Web Development|pages=1–11 |isbn=978-1-6654-4214-5 |s2cid=251657931 }}</ref> Mapping code idioms to [[idiosyncrasies]] can be a helpful way to navigate the tradeoffs between generalization and specificity. By identifying common patterns and idioms, developers can create mental models and schemata that help them quickly understand and navigate new code. Furthermore, by mapping these idioms to idiosyncrasies and specific use cases, developers can ensure that they are applying the correct approach and not overgeneralizing it.
==Examples of simple idioms==
One way to do this is by creating a reference or documentation that maps common idioms to specific use cases, highlighting where they may need to be adapted or modified to fit a particular project or development team. This can help ensure that developers are working with a shared understanding of best practices and can make informed decisions about when to use established idioms and when to adapt them to fit their specific needs.


A common misconception is to use the [[adverb]]ial or [[Adjective|adjectival]] form of the term as ''using a programming language in a typical way'', which really refers to a idiosyncrasy. An idiom implies the semantics of some code in a programming language has similarities to other languages or frameworks. For example, an '''idiosyncratic''' way to [[C dynamic memory allocation|manage dynamic memory]] in [[C (programming language)|C]] would be to use the [[C standard library]] functions ''malloc'' and ''free'', whereas '''idiomatic''' refers to manual [[memory management]] as recurring semantic role that can be achieved with code fragments ''malloc'' in C, or ''pointer = new type [number_of_elements]'' in C++. In both cases, the semantics of the code are intelligible to developers familiar with C or C++, once the idiomatic or idiosyncratic rationale is exposed to them. However, while idiomatic rationale is often general to the programming domain, idiosyncratic rationale is frequently tied to specific API terminology.
===Incrementing a counter===


==Examples of simple idioms==
In virtually all languages that support [[Assignment (computer programming)|assignment]], a counter can be incremented using code such as this (for example in [[BASIC]]):
===Printing Hello World===

{{main|"Hello, World!" program}}
<source lang=freebasic>
One of the most common starting points to learn to program or notice the syntax differences between a known language and a new one.<ref>{{cite web|url=http://www.programming-idioms.org/idiom/1/print-hello-world|title=Print Hello World|website=www.programming-idioms.org}}</ref>
i = i + 1
</source>

As this is an extremely common operation, many languages provide specialized [[Operator (computer programming)|operators]] for this, notably the [[C (programming language)|C language]], and many others derived from it:

<source lang=C>
i += 1; /* i = i + 1; */
++i; /* same result */
i++; /* same result */
</source>

<small>There is a difference between the first two expressions, which yield the new version of <code>i</code>, and the third, which yields the old version of <code>i</code>. When the expressions are used as isolated statements, as in this example, the yielded value is ignored.</small>
[[Pascal (programming language)|Pascal]] instead provides a built-in procedure for the same operation:

<source lang=Pascal>
i := i + 1;
Inc(i); (* same *)
</source>

These are the ''idiomatic'' ways of "adding one to a counter".

===Swapping values between variables===
: ''Main article: [[Swap (computer science)]]''
In many languages, code for swapping the values in two variables looks like the following:

<code>
temp = a;
a = b;
b = temp;</code>

In [[Perl]], the list assignment syntax allows a more succinct expression:

<code>
($a, $b) = ($b, $a);</code>

Or even more concise in [[Python (programming language)|Python]],

<code>
a, b = b, a</code>

===Infinite loop===

The code used to write an [[infinite loop|infinite (nonterminating) loop]] varies widely between different programming languages, although it often takes the form of a [[while loop]] where the test condition is always true. In Pascal, for example:

<code>
while true do begin
do_something();
end;</code>

There are several ways to write an infinite loop in C, including a loop very similar to the Pascal example, but the following idiom uses the unusual appearance of the empty [[for loop]] condition to draw attention visually to the loop:

<code>
for (;;) {
do_something();
}</code>

Perl allows the C syntax above, but supports some other syntax as well. For example:

<code>
do_something() while (1); # Succinct one-line infinite loop
# same as
while (1) { do_something() };</code>

<code>
# Using a "naked block" and the redo operator
{
do_something();
redo;
}</code>

Ada loops forever this readable way:

<code>
loop
do_something;
end loop;</code>


It has several implementations, among them the code fragments for [[C++]]:
Also readable python syntax:
<syntaxhighlight lang=C++>
std::cout << "Hello World\n";
</syntaxhighlight>


For [[Java (programming language)|Java]]:
<code>
<syntaxhighlight lang=Java>
while True:
System.out.println("Hello World");
do_something()</code>
</syntaxhighlight>


===Set as associative array===
===Inserting an element in an array===
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.<ref>{{cite web|url=http://www.programming-idioms.org/idiom/44/insert-element-in-list|title=Insert element in list|website=www.programming-idioms.org}}</ref>
In languages that do not support the [[Set (abstract data type)|set data type]], but do support [[associative array]]s, 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 <code>1</code>).


Code fragments:
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 (abstract data type)|list]] or [[array data structure|array]] or not. Set membership in a list or (unsorted) array is an [[big O notation|''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]].


For [[Python (programming language)|Python]]:
The following idiom is commonly used to express this in Perl, which has fast associative arrays (implemented as hash tables), but no sets:
<syntaxhighlight lang=Java>
s.insert(i, x)
</syntaxhighlight>


For [[JavaScript]]:
<source lang=Perl>
<syntaxhighlight lang=Java>
my %elements = map { $_ => 1 } @elements;
s.splice(i, 0, x);
</source>
</syntaxhighlight>


For [[Perl]]:
===Pimpl idiom===
<syntaxhighlight lang=Perl>
splice(@s, $i, 0, $x)
</syntaxhighlight>


== See also ==
In OOP the implementation details of an API-level class can be hidden in an own implementation class. A pointer (or reference) to that class is stored in the API-level class.
* [[Algorithmic skeleton]]
* [[Embedded SQL]]
* [[Idiom (language structure)|Idiom]]


==References==
Read more in the article [[Opaque pointer]].
{{Reflist}}


== External links ==
== External links ==
* [http://www.programming-idioms.org programming-idioms.org] shows short idioms implementations in most mainstream languages.
* [https://programming-idioms.org programming-idioms.org] shows short idioms implementations in most mainstream languages.
* [http://en.wikibooks.org/wiki/C%2B%2B_Programming/Idioms C++ programming idioms] from Wikibooks.
* [https://en.wikibooks.org/wiki/C%2B%2B_Programming/Idioms C++ programming idioms] from Wikibooks.


{{DEFAULTSORT:Programming Idiom}}
{{DEFAULTSORT:Programming Idiom}}
[[Category:Programming idioms|*]]
[[Category:Programming idioms| ]]

Latest revision as of 03:11, 16 November 2023

In computer programming, a programming idiom or code idiom is a group of code fragments sharing an equivalent semantic role,[1] which recurs frequently across software projects often expressing a special feature of a recurring construct in one or more programming languages or libraries. This definition is rooted in the definition of "idiom" as used in the field of linguistics. Developers recognize programming idioms by associating meaning (semantic role) to one or more syntactical expressions within code snippets (code fragments). The idiom can be seen as an action on a programming 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's semantic role 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. It also helps to transfer knowledge in the form of analogies from one language or framework to another. Such idiomatic knowledge is widely used in crowdsourced repositories to help developers overcome programming barriers.[2] Mapping code idioms to idiosyncrasies can be a helpful way to navigate the tradeoffs between generalization and specificity. By identifying common patterns and idioms, developers can create mental models and schemata that help them quickly understand and navigate new code. Furthermore, by mapping these idioms to idiosyncrasies and specific use cases, developers can ensure that they are applying the correct approach and not overgeneralizing it. One way to do this is by creating a reference or documentation that maps common idioms to specific use cases, highlighting where they may need to be adapted or modified to fit a particular project or development team. This can help ensure that developers are working with a shared understanding of best practices and can make informed decisions about when to use established idioms and when to adapt them to fit their specific needs.

A common misconception is to use the adverbial or adjectival form of the term as using a programming language in a typical way, which really refers to a idiosyncrasy. An idiom implies the semantics of some code in a programming language has similarities to other languages or frameworks. For example, an idiosyncratic way to manage dynamic memory in C would be to use the C standard library functions malloc and free, whereas idiomatic refers to manual memory management as recurring semantic role that can be achieved with code fragments malloc in C, or pointer = new type [number_of_elements] in C++. In both cases, the semantics of the code are intelligible to developers familiar with C or C++, once the idiomatic or idiosyncratic rationale is exposed to them. However, while idiomatic rationale is often general to the programming domain, idiosyncratic rationale is frequently tied to specific API terminology.

Examples of simple idioms

[edit]

Printing Hello World

[edit]

One of the most common starting points to learn to program or notice the syntax differences between a known language and a new one.[3]

It has several implementations, among them the code fragments for C++:

std::cout << "Hello World\n";

For Java:

System.out.println("Hello World");

Inserting an element in an array

[edit]

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.[4]

Code fragments:

For Python:

s.insert(i, x)

For JavaScript:

s.splice(i, 0, x);

For Perl:

splice(@s, $i, 0, $x)

See also

[edit]

References

[edit]
  1. ^ Allamanis, Miltiadis; Sutton, Charles (2014). "Mining idioms from source code". Proceedings of the 22nd ACM SIGSOFT International Symposium on Foundations of Software Engineering. pp. 472–483. arXiv:1404.0417. doi:10.1145/2635868.2635901. ISBN 9781450330565. S2CID 2923536.
  2. ^ Samudio, David I.; Latoza, Thomas D. (2022). "Barriers in Front-End Web Development" (PDF). 2022 IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC). pp. 1–11. doi:10.1109/VL/HCC53370.2022.9833127. ISBN 978-1-6654-4214-5. S2CID 251657931.
  3. ^ "Print Hello World". www.programming-idioms.org.
  4. ^ "Insert element in list". www.programming-idioms.org.
[edit]