Named parameter

Last updated

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 parameter within the function call.

Contents

Overview

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

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:

structA{inta{},intb{}};voidfoo(Abar){std::cout<<bar.a<<bar.b;}foo({.a=1,.b=3});

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.

Optional parameters and positional 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, 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.

In MediaWiki, the codes (variables) {{{1}}}, {{{2}}} in templates and so on, will be replaced by the first, second, and so on unnamed parameter (or the value of a parameter named 1, 2, etc.); these are known as positional parameters.

Emulating

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

With documentation

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

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]

structMyParam{intxPosition;intyPosition;intwidth;intheight;unsignedchardrawingNow;};MyParamparameters={.xPosition=20,.yPosition=50,.width=100,.height=5,.drawingNow=TRUE};MyFunctionCall(&parameters);

Special Support

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

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

Related Research Articles

In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.

In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance.

Programming style, also known as code style, is a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers read and understand source code conforming to the style, and help to avoid introducing errors.

In computer science, a type signature or type annotation defines the inputs and outputs for a function, subroutine or method. A type signature includes the number, types, and order of the arguments required by a function. A type signature is typically used during overload resolution for choosing the correct definition of a function to be called among many overloaded forms.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full. Later languages allow the programmer to specify default arguments that always have a value, even if one is not specified when calling the function.

<span class="mw-page-title-main">C syntax</span> Set of rules defining correctly structured programs

The syntax of the C programming language is the set of rules governing writing of software in C. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

<span class="mw-page-title-main">Raku (programming language)</span> Programming language derived from Perl

Raku is a member of the Perl family of programming languages. Formerly known as Perl 6, it was renamed in October 2019. Raku introduces elements of many modern and historical languages. Compatibility with Perl was not a goal, though a compatibility mode is part of the specification. The design process for Raku began in 2000.

In computer programming, a nested function is a function which is defined within another function, the enclosing function. Due to simple recursive scope rules, a nested function is itself invisible outside of its immediately enclosing function, but can see (access) all local objects of its immediately enclosing function as well as of any function(s) which, in turn, encloses that function. The nesting is theoretically possible to unlimited depth, although only a few levels are normally used in practical programs.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

This article compares a large number of programming languages by tabulating their data types, their expression, statement, and declaration syntax, and some common operating-system interfaces.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

This comparison of programming languages compares how object-oriented programming languages such as C++, Java, Smalltalk, Object Pascal, Perl, Python, and others manipulate data structures.

In computer science, partial application refers to the process of fixing a number of arguments of a function, producing another function of smaller arity. Given a function , we might fix the first argument, producing a function of type . Evaluation of this function might be represented as . Note that the result of partial function application in this case is a function that takes two arguments. Partial application is sometimes incorrectly called currying, which is a related, but distinct concept.

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.

In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.

Kotlin is a cross-platform, statically typed, general-purpose high-level programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code via LLVM. Language development costs are borne by JetBrains, while the Kotlin Foundation protects the Kotlin trademark.

Swift is a high-level general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

Flix is a functional, imperative, and logic programming language developed at Aarhus University, with funding from the Independent Research Fund Denmark, and by a community of open source contributors. The Flix language supports algebraic data types, pattern matching, parametric polymorphism, currying, higher-order functions, extensible records, channel and process-based concurrency, and tail call elimination. Two notable features of Flix are its type and effect system and its support for first-class Datalog constraints.

References

  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"?