When verbally talking about methods, I'm never sure whether to use the word argument or parameter or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms?
I'm a C# programmer, but I also wonder whether people use different terms in different languages.
For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read Code Complete because I'm asking this for the benefit of other people who don't already have a copy of Steve McConnell's marvellous book.)
Summary
The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "formal argument/parameter" and "actual argument/parameter" to disambiguate.
A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.
public void MyMethod(string myParam) { }
...
string myArg1 = "this is my argument";
myClass.MyMethod(myArg1);
Parameter is the variable in the declaration of the function.
Argument is the actual value of this variable that gets passed to the function.
Simple:
PARAMETER → PLACEHOLDER (This means a placeholder belongs to the function naming and be used in the function body)
ARGUMENT → ACTUAL VALUE (This means an actual value which is passed by the function calling)
A parameter is a variable in the declaration of the function.
An argument is the actual value of the variable that gets passed to the function.
There is already a Wikipedia entry on the subject (see Parameter) that defines and distinguishes the terms parameter and argument. In short, a parameter is part of the function/procedure/method signature and an argument is the actual value supplied at run-time and/or call-site for the parameter.
The Wikipedia article also states that the two terms are often used synonymously (especially when reasoning about code informally):
Although parameters are also commonly
referred to as arguments, arguments
are more properly thought of as the
actual values or references assigned
to the parameter variables when the
subroutine is called at runtime.
Given the following example function in C that adds two integers, x and y would be referred to as its parameters:
int add(int x, int y) {
return x + y;
}
At a call-site using add, such as the example shown below, 123 and 456 would be referred to as the arguments of the call.
int result = add(123, 456);
Also, some language specifications (or formal documentation) choose to use parameter or argument exclusively and use adjectives like formal and actual instead to disambiguate between the two cases. For example, C/C++ documentation often refers to function parameters as formal arguments and function call arguments as actual arguments. For an example, see “Formal and Actual Arguments” in the Visual C++ Language Reference.
A parameter is something you have to fill in when you call a function. What you put in it is the argument.
Simply set: the argument goes into the parameter, an argument is the value of the parameter.
A bit more info on:
http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments
The use of the terms parameters and arguments have been misused
somewhat among programmers and even authors. When dealing with
methods, the term parameter is used to identify the placeholders in
the method signature, whereas the term arguments are the actual
values that you pass in to the method.
MCSD Cerfification Toolkit (Exam 70-483) Programming in C#, 1st edition, Wrox, 2013
Real-world case scenario
// Define a method with two parameters
int Sum(int num1, int num2)
{
return num1 + num2;
}
// Call the method using two arguments
var ret = Sum(2, 3);
Let's say you're an airline. You build an airplane. You install seats in it. Then, you fill the plane up with passengers and send it somewhere. The passengers disembark. Next day, you re-use the same plane, and same seats, but with different passengers this time.
The plane is your function.
The parameters are the seats.
The arguments are the passengers that go in those seats.
function fly(seat1, seat2) {
seat1.sayMyName();
// Estraven
seat2.sayMyName();
etc.
}
var passenger1 = "Estraven";
var passenger2 = "Genly Ai";
fly(passenger1, passenger2);
Generally speaking, the terms parameter and argument are used interchangeably to mean information that is passed into a function.
Yet, from a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Always Remember that:
Arguments are passed while parameters are received.
In editing, I'm often put off at how people forget: structure languages are based on natural languages.
In English
A "parameter" is a placeholder. They set the response format, in spoken language. By definition, it's party to the call, limiting the response.
An "argument" is a position that is being considered. You argue your opinion: you consider an argument.
Main difference
The thematic role of an argument is agent. The thematic role of parameter is recipient.
Interactions
Think of the argument as the male part, making the parameter the female part. The argument goes into the parameter.
Usage
A parameter is usually used in definitions. An argument is usually used in invocations.
Questions
Finish the sentence to make it less dissonant.
(A) Speaking of a definition:
What argument will be used []?
What [] will this parameter []?
(B) Speaking of an invocation:
What parameter will you use, []?
What [] will be [] this parameter?
Answers
(A)
on/in/against/with this parameter
argument(s) ... take
(B)
and what are some example arguments
argument(s) ... used on/in/against/with
Overlaps
As you can imagine, after answering: in spoken language, these words will sometimes produce identical responses!
So, as a rule:
Usually if someone wants parameter information, they want to know more about the type, the variable name, etc. They may become confused if you only give example arguments.
Usually if someone wants argument information, they want to know what value you passed to a function or its parameter(s).
Or maybe it's even simpler to remember like this, in case of optional arguments for a method:
public void Method(string parameter = "argument")
{
}
parameter is the parameter, its value, "argument" is the argument :)
This example might help.
int main () {
int x = 5;
int y = 4;
sum(x, y); // **x and y are arguments**
}
int sum(int one, int two) { // **one and two are parameters**
return one + two;
}
The parameters of a function/method describe to you the values that it uses to calculate its result.
The arguments of a function are the values assigned to these parameters during a particular call of the function/method.
Parameters and Arguments
All the different terms that have to do with parameters and arguments
can be confusing. However, if you keep a few simple points in mind,
you will be able to easily handle these terms.
The formal parameters for a function are listed in the function declaration and are used in the body of the function definition. A
formal parameter (of any sort) is a kind of blank or placeholder that
is filled in with something when the function is called.
An argument is something that is used to fill in a formal parameter.
When you write down a function call, the arguments are listed in
parentheses after the function name. When the function call is
executed, the arguments are plugged in for the formal parameters.
The terms call-by-value and call-by-reference refer to the mechanism
that is used in the plugging-in process. In the call-by-value method
only the value of the argument is used. In this call-by-value
mechanism, the formal parameter is a local variable that is
initialized to the value of the corresponding argument. In the
call-by-reference mechanism the argument is a variable and the
entire variable is used. In the call- by-reference mechanism the
argument variable is substituted for the formal parameter so that
any change that is made to the formal parameter is actually made to
the argument variable.
Source: Absolute C++, Walter Savitch
That is,
The terms are somewhat interchangeable. The distinction described in other answers is more properly expressed with the terms formal parameter for the name used inside the body of the function and parameter for the value supplied at the call site (formal argument and argument are also common).
Also note that, in mathematics, the term argument is far more common and parameter usually means something quite different (though the parameter in a parametric equation is essentially the argument to two or more functions).
An argument is an instantiation of a parameter.
Yes! Parameters and Arguments have different meanings, which can be easily explained as follows:
Function Parameters are the names listed in the function definition.
Function Arguments are the real values passed to (and received by) the function.
Simple Explanations without code
A "parameter" is a very general, broad thing, but an "argument: is a very specific, concrete thing. This is best illustrated via everyday examples:
Example 1: Vending Machines - Money is the parameter, $2.00 is the argument
Most machines take an input and return an output. For example a vending machine takes as an input: money, and returns: fizzy drinks as the output. In that particular case, it accepts as a parameter: money.
What then is the argument? Well if I put $2.00 into the machine, then the argument is: $2.00 - it is the very specific input used.
Example 2: Cars - Petrol is the parameter
Let's consider a car: they accept petrol (unleaded gasoline) as an input. It can be said that these machines accept parameters of type: petrol. The argument would be the exact and concrete input I put into my car. e.g. In my case, the argument would be: 40 litres of unleaded petrol/gasoline.
Example 3 - Elaboration on Arguments
An argument is a particular and specific example of an input. Suppose my machine takes a person as an input and turns them into someone who isn't a liar.
What then is an argument? The argument will be the particular person who is actually put into the machine. e.g. if Colin Powell is put into the machine then the argument would be Colin Powell.
So the parameter would be a person as an abstract concept, but the argument would always be a particular person with a particular name who is put into the machine. The argument is specific and concrete.
That's the difference. Simple.
Confused?
Post a comment and I'll fix up the explanation.
They both dont have much difference in usage in C, both the terms are used
in practice.
Mostly arguments are often used with functions. The value passed with the function calling statement is called the argument, And the parameter would be the variable which copies the value in the function definition (called as formal parameter).
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
In the above code num1 and num2 are formal parameters and a and b are actual arguments.
Oracle's Java tutorials define this distinction thusly:
"Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order."
A more detailed discussion of parameters and arguments:
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Logically speaking,we're actually talking about the same thing.
But I think a simple metaphor would be helpful to solve this dilemma.
If the metaphors can be called various connection point we can equate them to plug points on a wall.
In this case we can consider parameters and arguments as follows;
Parameters are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them.
Arguments will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments.
I'm still not happy with all these answers. They all start talking about "function declarations" and my monkey brain has already wandered off and started thinking about unicorns. That doesn't help me remember at all, it's just the definition.
I want something that I can immediately and forever hold in my head.
The only answer here that I quickly understand is:
"Arguments are actual values that are passed in".
Arguments are easier to define and as long as you know what they are then you know parameters are the other.
The other way I can think of it is:
Arguments are the variables outside the function
Parameters are the variables inside the function
Simplified down to:
Arguments outside, parameters inside
If any one wants to disagree with me, you can leave your arguments outside ;)
When we create the method (function) in Java, the method like this..
data-type name of the method (data-type variable-name)
In the parenthesis, these are the parameters, and when we call the method (function) we pass the value of this parameter, which are called the arguments.
According to Joseph's Alabahari book "C# in a Nutshell" (C# 7.0, p. 49) :
static void Foo (int x)
{
x = x + 1; // When you're talking in context of this method x is parameter
Console.WriteLine (x);
}
static void Main()
{
Foo (8); // an argument of 8.
// When you're talking from the outer scope point of view
}
In some human languages (afaik Italian, Russian) synonyms are widely used for these terms.
parameter = formal parameter
argument = actual parameter
In my university professors use both kind of names.
It's explained perfectly in Parameter (computer programming) - Wikipedia
Loosely, a parameter is a type, and an argument is an instance.
In the function definition f(x) = x*x the variable x is a parameter; in the function call f(2) the value ``2 is the argument of the function.
And Parameter - Wikipedia
In computer programming, two notions of parameter are commonly used, and are referred to as parameters and arguments—or more formally as a formal parameter and an actual parameter.
For example, in the definition of a function such as
y = f(x) = x + 2,
x is the formal parameter (the parameter) of the defined function.
When the function is evaluated for a given value, as in
f(3): or, y = f(3) = 3 + 2 = 5,
is the actual parameter (the argument) for evaluation by the defined function; it is a given value (actual value) that is substituted for the formal parameter of the defined function. (In casual usage the terms parameter and argument might inadvertently be interchanged, and thereby used incorrectly.)
Parameter is a variable in a function definition
Argument is a value of parameter
<?php
/* define function */
function myFunction($parameter1, $parameter2)
{
echo "This is value of paramater 1: {$parameter1} <br />";
echo "This is value of paramater 2: {$parameter2} <br />";
}
/* call function with arguments*/
myFunction(1, 2);
?>
Or even simpler...
Arguments in !
Parameters out !
I thought it through and realized my previous answer was wrong. Here's a much better definition
{Imagine a carton of eggs: A pack of sausage links: And a maid } These represent elements of a Function needed for preparation called : (use any name: Lets say Cooking is the name of my function).
A Maid is a method .
( You must __call_ or ask this method to make breakfast)(The act of making breakfast is a Function called Cooking)_
Eggs and sausages are Parameters :
(because the number of eggs and the number of sausages you want to eat is __variable_ .)_
Your decision is an Argument :
It represents the __Value_ of the chosen number of eggs and/or sausages you are Cooking ._
{Mnemonic}
_" When you call the maid and ask her to make breakfast, she __argues_ with you about how many eggs and sausages you should eating. She's concerned about your cholesterol" __
( Arguments , then, are the values for the combination of Parameters you have declared and decided to pass to your Function )
Parameters are the variables received by a function.Hence they are visible in function declaration.They contain the variable name with their data type.
Arguments are actual values which are passed to another function. thats why we can see them in function call. They are just values without their datatype
I want to implement a method inside a class like this:
class Query {
public function orderBy($dir="asc", ...$fields){}
}
Where $dir is a default argument and $field is a variable-length argument using (...) token.
The problem is that variable-length argument must be declared at the end, and when I do this, the developer can’t skip the first argument to its default. How can I fix this?
Note that I don’t want to use func_get_args() because I want the developer to have some type hints.
This is simply not doable. PHP does not support this, and it doesn't make a lot of sense that it would. The only way this could work is by having named arguments, as in some other languages, making argument order irrelevant.
Furthermore, your requirment of using a variadic argument there is artificial, and not very useful. Just use an array and an optional order argument.
E.g.:
function orderBy(array $columns, string $order = 'asc') {
// do your thing
}
Neater, simpler to understand to the method users, and complies with the language syntax.
If you want it to look "similar" to a variadic function, just call the method using a syntax like this:
orderBy(["column1", "column5"]);
orderBy(["column2"], 'desc');
What I wanted to do was:
function tableHead($id=NULL, $class=NULL, ...$columnsHeads)
the "logical" function call when the first two arguments were not wanted to me was:
tableHead( , , "Dogs","Cars","Sausages");
Sadly PHP does not let you use a , as an empty default value. I get round this by sticking a NULL, NULL, as the first 2 arguments. Not ideal but will do for now!
(I am sure I have used empty , in some language 20 years ago to send an empty value - anyone know? - Or is it just wishful thinking?)
My SOLUTION (haha) is:
tableHead(NULL, NULL, "dogs","cars", "sausages");
Not ideal but it works. In normal usage the function will be called with id and class specified by variables. Personally I do not see anything unholy about combining variadic and optional arguments ... but you do have to be a bit careful!
Is there any directive in the recent PHPs (maybe similar to that of declare( strict_types = 1 );) that tells the PHP interpreter to "force" return types in the functions, and if there's no return type, it fails due to a parse/syntax error?
I'd like that having this in the code:
public function add( int $a, int $b ) : int
{
return $a + $b;
}
is allowed but this one:
public function add( int $a, int $b )
{
return $a + $b;
}
is forbidden by the interpreter resulting in a parse error so the script never gets executed even if the function is not called.
I mean:
It is not that I want to "force a return type in a certain function" (I already do that). What I want is that the configuration "forces me to force return types in all the functions of a file or project".
I had a look at PHP RFC: Return Type Declarations and there is no way (for now and for future release) to do such a thing ...
It's the same for declare(strict_types=1) (PHP RFC: Scalar Type Declarations) which only ensure that the existing declarations are strictly typed checked.
The short answer to your question is No. PHP doesn't have anything to force you to define your return type. It also doesn't have anything to force you to define types for your arguments either -- strict_types = 1 forces passed values to be of the correct type for the method if the type is defined, but you can still write methods with arguments that don't define a type.
It is possible that PHP may make changes in a future release along the lines you're looking for, but it isn't on the cards for any version right now.
In the meanwhile, I would suggest using a code checking tool to help you enforce this kind of detail in your code. A tool like PHP Code Sniffer will be a good start. You can add it to your IDE so that you get warnings in real time when your code doesn't meet your defined standards, and you can add it to your workflow so that it prevents code from being committed and/or deployed if it fails the test.
What exactly is your problem with not having a forced fixed return type? I like the lazy way of coding with PHP. I could be cumbersome in large projects to find a mistyped variable name or wrong typed return value I admit. But there are remedies to that.
If a caller expects a definitive type it can (must!) test it anyway. This could be done by converting the result to the requested type and throwing an exception on failure as shown in PHP String-to-Integer Exception. Or in case of integer simply using is_numeric, is_nan, is_real etc.. You can put those tests in member functions for each type in the base object or even use a global singleton tester object with those member functions etc..
My apologies if the title isn't clear, but I find this difficult to describe. Basically, I have a function that looks for an instance of a class (the school kind) given a class ID number and a date. The function can also create a new class instance if desired.
function get_class_instance($class_id, $date, $create)
Inside the function is a database select on the class_instances table using the class_id and date as arguments. If a matching class_instance is found, its ID is returned. If none is found, there's a conditional for the create argument. If it's true, a new class_instance is created using a database insert and its ID is returned. If false, nothing is changed in the database and false is returned.
I'm still a beginner with PHP and coding generally, so I'm thinking there is probably a better way. The issue is that when calling the function, it might not be clear to someone why there is a boolean being passed.
$original_cinstance_id = get_class_instance($original_class_id, $original_date, 1);
Passing boolean flags to functions to make them do two different things instead of just one is considered a Code Smell in Robert Martin's Clean Code book. The suggested better option would be to have two functions get_whatever and create_whatever.
While a Code Smell depends on context, I think the boolean flag smell does apply in this case, because creating something is different from merely reading it. The former is a Command and the latter is a Query. So they should be separated. One changes state, the other doesn't. It makes for better semantics and separation of concerns to split them. Also, it will reduce the Cyclomatic Complexity of the function by one branch, so you will need one unit-test less to cover it.
Quoting https://martinfowler.com/bliki/FlagArgument.html
Boolean arguments loudly declare that the function does more than one thing. They are confusing and should be eliminated.
Quoting http://www.informit.com/articles/article.aspx?p=1392524
My reasoning here is that the separate methods communicate more clearly what my intention is when I make the call. Instead of having to remember the meaning of the flag variable when I see book(martin, false) I can easily read regularBook(martin).
Additional discussion and reading material:
https://softwareengineering.stackexchange.com/questions/147977/is-it-wrong-to-use-a-boolean-parameter-to-determine-behavior
https://medium.com/#amlcurran/clean-code-the-curse-of-a-boolean-parameter-c237a830b7a3
https://8thlight.com/blog/dariusz-pasciak/2015/05/28/alternatives-to-boolean-parameters.html
You can use a default value for create, so if you pass anything to it, it acts as a normal "get" operation for the database. Like this:
function get_class_instance($class_id, $date, $create = false);
You can query your ID's like this:
$class_id = get_class_instance(1, "18-10-2017");
You can then pass "true" to it whenever you need to create it on the database:
$class_id = get_class_instance(1, "18-10-2017", true);
Instead of passing a number value, you can pass a real boolean value like this:
$original_cinstance_id = get_class_instance($original_class_id, $original_date, true);
Also in the declaration of your function, you can specify a default value to avoid to pass the boolean each time:
function get_class_instance($class_id, $date, $create = false)
one option is to create an enumerator like so:
abstract class create_options {
const no_action = 0;
const create = 1;
}
so now your function call would look like this:
$original_cinstance_id = get_class_instance($original_class_id, $original_date, create_options::no_action);
in practice as long as your code is well commented then this isn't a major issue with boolean flags, but if you had a dozen possible options with different results then this could be useful.
As others have mentioned, in many languages you can also make an argument optional, and have a default behavior unless the caller specifically defines that argument.
In a PHP web application I'm working on, I see functions defined in two possible ways.
Approach 1:
function myfunc($arg1, $arg2, $arg3)
Approach 2:
// where $array_params has the structure array('arg1'=>$val1, 'arg2'=>$val2, 'arg3'=>$val3)
function myfunc($array_params)
When should I use one approach over another? It seems that if system requirements keep changing, and therefore the number of arguments for myfunc keep changing, approach 1 may require a lot of maintenance.
If the system is changing so often that using an indexed array is the best solution, I'd say this is the least of your worries. :-)
In general functions/methods shouldn't take too many arguments (5 plus or minus 2 being the maximum) and I'd say that you should stick to using named (and ideally type hinted) arguments. (An indexed array of arguments only really makes sense if there's a large quantity of optional data - a good example being configuration information.)
As #Pekka says, passing an array of arguments is also liable to be a pain to document and therefore for other people/yourself in 'n' months to maintain.
Update-ette...
Incidentally, the oft mentioned book Code Complete examines such issues in quite a bit of detail - it's a great tome which I'd highly recommend.
Using a params array (a surrogate for what is called "named arguments" in other languages") is great - I like to use it myself - but it has a pretty big downside: Arguments are not documentable using standard phpDoc notation that way, and consequently, your IDE won't be able to give you hints when you type in the name of a function or method.
I find using an optional array of arguments to be useful when I want to override a set of defaults in the function. It might be useful when constructing an object that has a lot of different configuration options or is just a dumb container for information. This is something I picked up mostly from the Ruby world.
An example might be if I want to configure a container for a video in my web page:
function buildVideoPlayer($file, $options = array())
{
$defaults = array(
'showAds' => true,
'allowFullScreen' = true,
'showPlaybar' = true
);
$config = array_merge($defaults, $options);
if ($config['showAds']) { .. }
}
$this->buildVideoPlayer($url, array('showAds' => false));
Notice that the initial value of $options is an empty array, so providing it at all is optional.
Also, with this method we know that $options will always be an array, and we know those keys have defaults so we don't constantly need to check is_array() or isset() when referencing the argument.
with the first approach you are forcing the users of your function to provide all the parameters needed. the second way you cannot be sure that you got all you need. I would prefer the first approach.
If the parameters you're passing in can be grouped together logically you could think about using a parameter object (Refactoring, Martin Fowler, p295), that way if you need to add more parameters you can just add more fields to your parameter class and it won't break existing methods.
There are pros and cons to each way.
If it's a simple function that is unlikely to change, and only has a few arguments, then I would state them explicitly.
If the function has a large number of arguments, or is likely to change a lot in the future, then I would pass an array of arguments with keys, and use that. This also becomes helpful if you have function where you only need to pass some of the arguments often.
An example of when I would choose an array over arguments, for an example, would be if I had a function that created a form field. possible arguments I may want:
Type
Value
class
ID
style
options
is_required
and I may only need to pass a few of these. for example, if a field is type = text, I don't need options. I may not always need a class or a default value. This way It is easier to pass in several combinations of arguments, without having a function signature with a ton arguments and passing null all the time. Also, when HTML 5 becomes standard many many years from now, I may want to add additional possible arguments, such as turning auto-complete on or off.
I know this is an old post, but I want to share my approach. If the variables are logically connected in a type, you can group them in a class, and pass an object of them to the function. for example:
class user{
public $id;
public $name;
public $address;
...
}
and call:
$user = new user();
$user->id = ...
...
callFunctions($user);
If a new parameter is needed you can just add it in the class and the the function signature doesn't need to change.