Jump to content

Named parameter: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Optional parameters and positional parameters: not finding a primary source discussing it; the text had been taken from Help:Template so if anybody wishes to restore it they'll need to attribute
 
(59 intermediate revisions by 40 users not shown)
Line 1: Line 1:
{{Short description|Concept in computer programming}}
{{refimprove|date=August 2014}}
{{more citations needed|date=August 2014}}


In [[computer programming]], '''named parameters''', '''pass-by-name''', or '''keyword arguments''' refer to a computer language's support for function calls that clearly state the name of each [[Parameter (computer science)|parameter]] within the function call itself.
In [[computer programming]], '''named parameters''', '''named-parameter arguments''', '''named arguments''' or '''keyword arguments''' refer to a computer language's support for function calls to clearly associate each [[Parameter_(computer_programming)|argument]] with a given [[Parameter (computer science)|parameter]] within the function call.


== Overview ==
== Overview ==
A function call using named parameters differs from a regular function call in that the values are passed by associating each one with a parameter name, instead of providing an ordered list of values.
A function call using named parameters differs from a regular function call in that the arguments are passed by associating each one with a parameter name, instead of providing an ordered list of arguments.


For example, consider the following [[Java (programming language)|Java]] method call that does not use named parameters:
For example, consider this [[Java (programming language)|Java]] or [[C Sharp (programming language)|C#]] method call that doesn't use named parameters:

<source lang="java">
<syntaxhighlight lang="java">
window.addNewControl("Title", 20, 50, 100, 50, true);
window.addNewControl("Title", 20, 50, 100, 50, true);
</syntaxhighlight>
</source>


Using named parameters in [[Objective-C]], the call can be written as:
Using named parameters in [[Python (programming language)|Python]], the call can be written as:
<source lang="objc">
<syntaxhighlight lang="python">
[window addNewControlWithTitle:@"Title"
window.addNewControl(title="Title",
xPosition:20
xPosition=20,
yPosition:50
yPosition=50,
width:100
width=100,
height:50
height=50,
drawingNow:YES];
drawingNow=True)
</syntaxhighlight>
</source>
Using named parameters in [[PHP]], the call can be written as:

<syntaxhighlight lang="php">
The Objective-C version is more explicit, while the Java version is more concise. Depending on the particular instance, a programmer may find one or the other easier to read.
$window->addNewControl(title: "Title",
xPosition: 20,
yPosition: 50,
width: 100,
height: 50,
drawingNow: True);
</syntaxhighlight>
The version with positional arguments is more implicit. The versions that name parameters are more explicit. Depending on circumstance, a programmer may find one or the other to be easier to read.


== Use in programming languages ==
== Use in programming languages ==
Named parameters are supported explicitly in many languages. A non-exhaustive selection of examples includes [[Ada (programming language)|Ada]],<ref>{{cite book|author=|year=1983|title=Reference Manual for the Ada Programming Language|publisher=United States Department of Defense|isbn=}}</ref> [[C Sharp 4.0|C# 4.0+]],<ref>{{Cite web|last=BillWagner|title=Named and Optional Arguments - C# Programming Guide|url=https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments|access-date=2021-06-16|website=Microsoft Learn|language=en-us}}</ref> [[Ceylon (programming language)|Ceylon]]{{Citation needed|date=July 2021}}, [[ColdFusion Markup Language]] (CFML){{Citation needed|date=July 2021}}, [[Common Lisp]],<ref>{{Cite web|title=Functions|url=https://lispcookbook.github.io/cl-cookbook/functions.html|access-date=2021-10-28|website=The Common Lisp Cookbook }}</ref> [[Fortran]]{{Citation needed|date=July 2021}}, [[IDL (programming language)|IDL]]{{Citation needed|date=July 2021}}, [[Kotlin (programming language)|Kotlin]],<ref>{{Cite web|title=Functions {{!}} Kotlin|url=https://www.jetbrains.com/idea/functions.html|access-date=2021-06-16|website=Kotlin Help|language=en-US}}{{dead link|date=December 2023}}</ref> [[Mathematica]]{{Citation needed|date=July 2021}}, [[PL/SQL]]{{Citation needed|date=July 2021}}, [[PowerShell]]{{Citation needed|date=July 2021}}, [[Python (programming language)|Python]],<ref>{{Cite web|title=8. Compound statements - 8.7. Function definitions |url=https://docs.python.org/3/reference/compound_stmts.html#function-definitions|access-date=2021-10-28|website=Python documentation }}</ref> [[R (programming language)|R]],<ref>{{Cite web|title=10.3 Named arguments and defaults|url=https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Named-arguments-and-defaults |publisher=The Comprehensive R Archive Network |access-date=2021-10-28|website=An Introduction to R}}</ref> [[PHP]],<ref>{{Cite web|title=PHP: Function arguments - Manual - Named Arguments |url=https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments|access-date=2021-06-16|website=PHP }}</ref> [[Ruby (programming language)|Ruby]],<ref>{{Cite web|title=Ruby 2 Keyword Arguments|url=https://thoughtbot.com/blog/ruby-2-keyword-arguments |first1=Ian C. |last1=Anderson |access-date=2021-10-28|website=thoughtbot |date=21 July 2014}}</ref> [[Scala (programming language)|Scala]],<ref>{{Cite web|title=Named Arguments|url=https://docs.scala-lang.org/tour/named-arguments.html|access-date=2021-06-16|website=Scala Documentation}}</ref> [[Smalltalk]]{{Citation needed|date=July 2021}}, [[Swift (programming language)|Swift]]<ref>{{Cite web|url=https://docs.swift.org/swift-book/LanguageGuide/Functions.html#ID166|title=Functions |website=The Swift Programming Language (Swift 5.1) |access-date=2020-01-27}}</ref> and [[Visual Basic]].<ref>{{Cite web|last=KathleenDollard|title=Passing Arguments by Position and by Name - Visual Basic|url=https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-position-and-by-name|access-date=2021-06-16|website=Microsoft Learn|language=en-us}}</ref> [[Objective-C]] does not have named parameters (even though parts of the method name may look like named parameters).<ref>''[https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW5|iOS Developer Library - The Implementation of a Class Provides Its Internal Behavior]''</ref>
Named parameters are explicitly supported in many languages: a non-exhaustive selection of examples would include [[Ada (programming language)|Ada]], [[C Sharp 4.0|C# 4.0+]], [[Adobe ColdFusion|Coldfusion]], [[Common Lisp]], [[Scala (programming language)|Scala]], [[Mathematica]], [[PL/SQL]], [[Python (programming language)|Python]], [[R (programming language)|R]], [[Smalltalk]], [[Fortran]], [[Visual Basic]], [[IDL (programming language)|IDL]], [[Swift (Apple programming language)|Swift]] and [[Objective-C|Objective C]].
<br>In [[C++]], you can achieve named parameters by using designated initializers since [[C++20]],<ref>{{Cite web|url=https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0329r4.pdf|title=Designated Initialization Wording}}</ref> like so:
<syntaxhighlight lang="cpp">
struct A {int a{}, int b{} };

void
foo(A bar)
{
std::cout << bar.a << bar.b;
}
foo({ .a = 1, .b = 3 });
</syntaxhighlight>


== Order of parameters ==
== Order of parameters ==
In languages that do not support named parameters, the ''order'' of arguments in a function call is necessarily fixed, since it is the only way that the language can identify which argument is intended to be used for which parameter.


With named parameters, it is usually possible to provide the arguments in any order, since the parameter name attached to each argument identifies its purpose. This reduces the [[connascence]] between parts of the program. A few languages support named parameters but still require the arguments to be provided in a specific order.
In languages without named parameters, the ''order'' of parameters in a function call is necessarily fixed, since it is the only way that the language can identify which value is intended to be used for which purpose.


== Optional parameters and positional parameters{{anchor|Optional_parameters}}==
With named parameters, it is usually possible to provide the values in any arbitrary order, since the name attached to each value identifies its purpose. A few languages such as [[Objective-C]] use named parameters but also require the parameters to be provided in a specific order.
{{Main article|Default argument}}
Named parameters are often used in conjunction with optional parameters. Without named parameters, optional parameters can only appear at the end of the parameter list, since there is no other way to determine which values have been omitted. In languages that support named optional parameters, however, programs may supply any subset of the available parameters, and the names are used to determine which values have been provided.


An added complication arises in languages such as [[OCaml]] that support both optional named parameters and [[partial application]]. It is impossible in general to distinguish between a function partly applied, and a function to which a subset of parameters have been provided. OCaml resolves this ambiguity by requiring a positional argument after all optional named-parameter arguments: its presence or absence is used to decide if the function has been fully or partly applied. If all parameters are optional, the implementor may solve the issue by adding a dummy positional parameter of type [[Unit type|unit]].
== Optional parameters ==

Named parameters are often used in conjunction with optional parameters. Without named parameters, optional parameters can only appear at the end of the parameter list, since there is no other way to determine which values have been omitted. In languages that support named optional parameters, however, the programmer may supply any subset of the available parameters, and the names are used to determine which values have been provided.

An additional complication arises in languages such as [[OCaml]] that support both optional named parameters and [[partial application]]: it is impossible in general to distinguish between a partially applied function and a function to which a subset of parameters have been provided. OCaml resolves this ambiguity by requiring a positional parameter to follow all optional named parameters: its presence or absence is used to decide whether the function has been fully or partially applied. If all parameters are optional, the implementor may solve the issue by adding a dummy positional parameter of type [[Unit type|unit]].


== Emulating ==
== Emulating ==
In languages without named parameters, some of the same benefits can be achieved in other ways.
In languages that do not support named parameters, some of the same benefits can be achieved in other ways.


=== With documentation ===
=== With documentation ===
Their value as documentation can be replicated by tooltips in IDEs for languages such as [[Java (programming language)|Java]], or with comments (in [[C (programming language)|C]]):
Their value as documentation can be replicated by tooltips in [[integrated development environment]]s (IDEs) for languages such as [[Java (programming language)|Java]], or with comments (in [[C (programming language)|C]]):
<source lang="c">
<syntaxhighlight lang="c">
MyFunctionCall(
MyFunctionCall(
20, /* x coordinate */
20, /* x coordinate */
Line 51: Line 71:
TRUE /* drawing now? */
TRUE /* drawing now? */
);
);
</syntaxhighlight>
</source>


But this does not provide any checking, and the order of arguments remains important.
Such comments are not checked for correctness and the order of arguments remains important.


=== With data structures ===
=== With data structures ===
Removing the argument order restriction, and the ability to leave some values unspecified, can be achieved by passing a [[record (computer science)|record]] or [[associative array]].


For example, in [[JavaScript]], these two calls are equivalent:
The removal of the argument order restriction, and the ability to leave some values unspecified, can be achieved by passing a [[record (computer science)|record]] or [[associative array]].
<syntaxhighlight lang="JavaScript">

For example, in [[JavaScript]], the following two calls are equivalent:
<source lang="JavaScript">
MyFunctionCall({ xPosition: 20, yPosition: 50, width: 100, height: 5,
MyFunctionCall({ xPosition: 20, yPosition: 50, width: 100, height: 5,
drawingNow: true });
drawingNow: true });
</syntaxhighlight>
</source>
<source lang="JavaScript">
<syntaxhighlight lang="JavaScript">
MyFunctionCall({ width: 100, height: 5, xPosition: 20, yPosition: 50,
MyFunctionCall({ width: 100, height: 5, xPosition: 20, yPosition: 50,
drawingNow: true });
drawingNow: true });
</syntaxhighlight>
</source>


Compare to C99:<ref>https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html</ref>
Compare to C99:<ref>{{Cite web|url=https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html|title = Designated Inits (Using the GNU Compiler Collection (GCC))}}</ref>
<source lang="c">
<syntaxhighlight lang="c">
struct MyParam {
struct MyParam {
int xPosition;
int xPosition;
Line 82: Line 101:
.width = 100, .height = 5, .drawingNow = TRUE };
.width = 100, .height = 5, .drawingNow = TRUE };
MyFunctionCall(&parameters);
MyFunctionCall(&parameters);
</syntaxhighlight>
</source>


==== Special Support ====
In Perl, there is a similar convention. Functions with long parameter lists often accept an associative array (called a ''hash'' in Perl) that contains some or all parameters

<ref>Perl Design Patterns TinyWiki, [http://perldesignpatterns.com/?NamedArguments NamedArguments]</ref>
In [[Perl]] and pre-2.0 [[Ruby (programming language)|Ruby]] a similar convention exists (generally called a ''hash'' or ''options hash''<ref>[https://docstore.mik.ua/orelly/perl/prog3/ch02_09.htm Programming Perl 2.9: Hashes]</ref>), with special support for omitting the delimiters within function calls. As an example, the core module's Net::FTP ''new'' function accepts a hash of optional arguments.<ref>[http://perldoc.perl.org/Net/FTP.html Perl core module Net::FTP]</ref>
.<ref>As an example, the core module [http://perldoc.perl.org/Net/FTP.html Net::FTP]'s "new" function accepts a hash of optional arguments.</ref>


=== With chained method calls ===
=== With chained method calls ===
In [[object-oriented programming]] languages, it is possible to use [[method chaining]] to simulate named parameters, as a form of [[fluent interface]]. Each named-parameter argument is replaced with a method on an "arguments" object that modifies and then returns the object. In C++, this is termed the ''named parameter idiom''.<ref>C++ FAQ, [http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.20 10.20 What is the "Named Parameter Idiom"?]</ref> The object may then be passed to a function that uses the arguments it contains.


[[Method chaining]] is often used in conjunction with the [[builder pattern]] as a way to override default values provided by the builder class.
In object-oriented languages, it is possible to use [[method chaining]] to simulate named parameters, as a form of [[fluent interface]]. Each named parameter is replaced with a method on a parameter object that modifies and then returns the object. In C++, this is known as the '''Named Parameter Idiom'''.<ref>C++ FAQ, [http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.20 10.20 What is the "Named Parameter Idiom"?]</ref>
The object may then be passed to a function that uses the parameters it contains.
When this approach is extended to handle optional named parameters with default values,
it is known as the [[Builder pattern]].


==See also==
==See also==

* [[Tag (programming)|Tag]]
* [[Help:Template#Handling parameters|Help:Template]] for named and positional parameters.
* [[Fluent interface]]
* [[Tag (programming)]]


==References==
==References==
{{reflist}}
{{Reflist}}


==External links==
==External links==
* http://web.archive.org/web/20070502112455/http://plg.uwaterloo.ca/~rgesteve/cforall/named_pars.html
* https://web.archive.org/web/20070502112455/http://plg.uwaterloo.ca/~rgesteve/cforall/named_pars.html
* In C++ this paradigm can be easily implemented: [http://www.boost.org/doc/libs/1_53_0/libs/parameter/doc/html/index.html Boost Parameter Library]
* In C++ this paradigm can be easily implemented: [http://www.boost.org/doc/libs/1_53_0/libs/parameter/doc/html/ Boost Parameter Library]
* [http://rosettacode.org/wiki/Named_parameters Named Parameters in various programming languages] at [[Rosetta Code]]
* [http://rosettacode.org/wiki/Named_parameters Named Parameters in various programming languages] at [[Rosetta Code]]


[[Category:Subroutines]]
[[Category:Subroutines]]
[[Category:Articles with example code]]
[[Category:Articles with example C code]]
[[Category:Articles with example JavaScript code]]
[[Category:Articles with example PHP code]]
[[Category:Articles with example Python (programming language) code]]

Latest revision as of 10:08, 31 August 2024

In computer programming, named parameters, named-parameter arguments, named arguments or keyword arguments refer to a computer language's support for function calls to clearly associate each argument with a given parameter within the function call.

Overview

[edit]

A function call using named parameters differs from a regular function call in that the arguments are passed by associating each one with a parameter name, instead of providing an ordered list of arguments.

For example, consider this Java or C# method call that doesn't use named parameters:

window.addNewControl("Title", 20, 50, 100, 50, true);

Using named parameters in Python, the call can be written as:

window.addNewControl(title="Title",
                     xPosition=20,
                     yPosition=50,
                     width=100,
                     height=50,
                     drawingNow=True)

Using named parameters in PHP, the call can be written as:

$window->addNewControl(title: "Title",
                       xPosition: 20,
                       yPosition: 50,
                       width: 100,
                       height: 50,
                       drawingNow: True);

The version with positional arguments is more implicit. The versions that name parameters are more explicit. Depending on circumstance, a programmer may find one or the other to be easier to read.

Use in programming languages

[edit]

Named parameters are supported explicitly in many languages. A non-exhaustive selection of examples includes Ada,[1] C# 4.0+,[2] Ceylon[citation needed], ColdFusion Markup Language (CFML)[citation needed], Common Lisp,[3] Fortran[citation needed], IDL[citation needed], Kotlin,[4] Mathematica[citation needed], PL/SQL[citation needed], PowerShell[citation needed], Python,[5] R,[6] PHP,[7] Ruby,[8] Scala,[9] Smalltalk[citation needed], Swift[10] and Visual Basic.[11] Objective-C does not have named parameters (even though parts of the method name may look like named parameters).[12]
In C++, you can achieve named parameters by using designated initializers since C++20,[13] like so:

struct A {int a{}, int b{} }; 

void
foo(A bar)
{
   std::cout << bar.a << bar.b;
}
foo({ .a = 1, .b = 3 });

Order of parameters

[edit]

In languages that do not support named parameters, the order of arguments in a function call is necessarily fixed, since it is the only way that the language can identify which argument is intended to be used for which parameter.

With named parameters, it is usually possible to provide the arguments in any order, since the parameter name attached to each argument identifies its purpose. This reduces the connascence between parts of the program. A few languages support named parameters but still require the arguments to be provided in a specific order.

Optional parameters and positional parameters

[edit]

Named parameters are often used in conjunction with optional parameters. Without named parameters, optional parameters can only appear at the end of the parameter list, since there is no other way to determine which values have been omitted. In languages that support named optional parameters, however, programs may supply any subset of the available parameters, and the names are used to determine which values have been provided.

An added complication arises in languages such as OCaml that support both optional named parameters and partial application. It is impossible in general to distinguish between a function partly applied, and a function to which a subset of parameters have been provided. OCaml resolves this ambiguity by requiring a positional argument after all optional named-parameter arguments: its presence or absence is used to decide if the function has been fully or partly applied. If all parameters are optional, the implementor may solve the issue by adding a dummy positional parameter of type unit.

Emulating

[edit]

In languages that do not support named parameters, some of the same benefits can be achieved in other ways.

With documentation

[edit]

Their value as documentation can be replicated by tooltips in integrated development environments (IDEs) for languages such as Java, or with comments (in C):

MyFunctionCall(
    20,  /* x coordinate */
    50,  /* y coordinate */
    100, /* width */
    5,   /* height */
    TRUE /* drawing now? */
);

Such comments are not checked for correctness and the order of arguments remains important.

With data structures

[edit]

Removing the argument order restriction, and the ability to leave some values unspecified, can be achieved by passing a record or associative array.

For example, in JavaScript, these two calls are equivalent:

MyFunctionCall({ xPosition: 20, yPosition: 50, width: 100, height: 5,
                 drawingNow: true });
MyFunctionCall({ width: 100, height: 5, xPosition: 20, yPosition: 50,
                 drawingNow: true });

Compare to C99:[14]

struct MyParam {
    int xPosition;
    int yPosition;
    int width;
    int height;
    unsigned char drawingNow;
};

MyParam parameters = { .xPosition = 20, .yPosition = 50,
        .width = 100, .height = 5, .drawingNow  = TRUE };
MyFunctionCall(&parameters);

Special Support

[edit]

In Perl and pre-2.0 Ruby a similar convention exists (generally called a hash or options hash[15]), with special support for omitting the delimiters within function calls. As an example, the core module's Net::FTP new function accepts a hash of optional arguments.[16]

With chained method calls

[edit]

In object-oriented programming languages, it is possible to use method chaining to simulate named parameters, as a form of fluent interface. Each named-parameter argument is replaced with a method on an "arguments" object that modifies and then returns the object. In C++, this is termed the named parameter idiom.[17] The object may then be passed to a function that uses the arguments it contains.

Method chaining is often used in conjunction with the builder pattern as a way to override default values provided by the builder class.

See also

[edit]

References

[edit]
  1. ^ Reference Manual for the Ada Programming Language. United States Department of Defense. 1983.
  2. ^ BillWagner. "Named and Optional Arguments - C# Programming Guide". Microsoft Learn. Retrieved 2021-06-16.
  3. ^ "Functions". The Common Lisp Cookbook. Retrieved 2021-10-28.
  4. ^ "Functions | Kotlin". Kotlin Help. Retrieved 2021-06-16.[dead link]
  5. ^ "8. Compound statements - 8.7. Function definitions". Python documentation. Retrieved 2021-10-28.
  6. ^ "10.3 Named arguments and defaults". An Introduction to R. The Comprehensive R Archive Network. Retrieved 2021-10-28.
  7. ^ "PHP: Function arguments - Manual - Named Arguments". PHP. Retrieved 2021-06-16.
  8. ^ Anderson, Ian C. (21 July 2014). "Ruby 2 Keyword Arguments". thoughtbot. Retrieved 2021-10-28.
  9. ^ "Named Arguments". Scala Documentation. Retrieved 2021-06-16.
  10. ^ "Functions". The Swift Programming Language (Swift 5.1). Retrieved 2020-01-27.
  11. ^ KathleenDollard. "Passing Arguments by Position and by Name - Visual Basic". Microsoft Learn. Retrieved 2021-06-16.
  12. ^ Developer Library - The Implementation of a Class Provides Its Internal Behavior
  13. ^ "Designated Initialization Wording" (PDF).
  14. ^ "Designated Inits (Using the GNU Compiler Collection (GCC))".
  15. ^ Programming Perl 2.9: Hashes
  16. ^ Perl core module Net::FTP
  17. ^ C++ FAQ, 10.20 What is the "Named Parameter Idiom"?
[edit]