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
Related
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!
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.
Why don't the function handling functions like call_user_func() support passing parameters by reference?
The docs say terse things like "Note that the parameters for call_user_func() are not passed by reference." I assume the PHP devs had some kind of reason for disabling that capability in this case.
Were they facing a technical limitation? Was it a language design choice? How did this come about?
EDIT:
In order to clarify this, here is an example.
<?php
function more(&$var){ $var++; }
$count = 0;
print "The count is $count.\n";
more($count);
print "The count is $count.\n";
call_user_func('more', $count);
print "The count is $count.\n";
// Output:
// The count is 0.
// The count is 1.
// The count is 1.
This is functioning normally; call_user_func does not pass $count by reference, even though more() declared it as a referenced variable. The call_user_func documentation clearly says that this is the way it's supposed to work.
I am well aware that I can get the effect I need by using call_user_func_array('more', array(&$count)).
The question is: why was call_user_func designed to work this way? The passing by reference documentation says that "Function definitions alone are enough to correctly pass the argument by reference." The behavior of call_user_func is an exception to that. Why?
The answer is embedded deep down in the way references work in PHP's model - not necessarily the implementation, because that can vary a lot, particularly in the 5.x versions. I'm sure you've heard the lines, they're not like C pointers, or C++ references, etc etc... Basically when a variable is assigned or bound, it can happen in two ways - either by value (in which case the new variable is bound to a new 'box' containing a copy of the old value), or by reference (in which case the new variable is bound to the same value box as the old value). This is true whether we're talking about variables, or function arguments, or cells in arrays.
Things start to get a bit hairy when you start passing references into functions - obviously the intent is to be able to modify the original variables. Quite some time ago, call-time pass-by-reference (the ability to pass a reference into a function that wasn't expecting one) got deprecated, because a function that wasn't aware it was dealing with a reference might 'accidentally' modify the input. Taking it to another level, if that function calls a second function, that itself wasn't expecting a reference... then everything ends up getting disconnected. It might work, but it's not guaranteed, and may break in some PHP version.
This is where call_user_func() comes in. Suppose you pass a reference into it (and get the associated the call-time pass-by-reference warning). Then your reference gets bound to a new variable - the parameters of call_user_func() itself. Then when your target function is called, its parameters are not bound where you expect. They're not bound to the original parameters at all. They're bound to the local variables that are in the call_user_func() declaration. call_user_func_array() requires caution too. Putting a reference in an array cell could be trouble - since PHP passes that array with "copy-on-write" semantics, you can't be sure if the array won't get modified underneath you, and the copy won't get detached from the original reference.
The most insightful explanation I've seen (which helped me get my head around references) was in a comment on the PHP 'passing by reference' manual:
http://ca.php.net/manual/en/language.references.pass.php#99549
Basically the logic goes like this. How would you write your own version of call_user_func() ? - and then explain how that breaks with references, and how it fails when you avoid call-time pass-by-reference. In other words, the right way to call functions (specify the value, and let PHP decide from the function declaration whether to pass value or reference) isn't going to work when you use call_user_func() - you're calling two functions deep, the first by value, and the second by reference to the values in the first.
Get your head around this, and you'll have a much deeper understanding of PHP references (and a much greater motivation to steer clear if you can).
See this:
http://hakre.wordpress.com/2011/03/09/call_user_func_array-php-5-3-and-passing-by-reference/
Is it possible to pass parameters by reference using call_user_func_array()?
http://bugs.php.net/bug.php?id=17309&edit=1
Passing references in an array works correctly.
Updated Answer:
You can use:
call_user_func('more', &$count)
to achieve the same effect as:
call_user_func_array('more', array(&$count))
For this reason I believe (unfoundedly) that call_user_func is just a compiler time short cut. (i.e. it gets replaced with the later at compile time)
To give my view on you actual question "Why was call_user_func designed to work this way?":
It probably falls under the same lines as "Why is some methods strstr and other str_replace?, why is array functions haystack, needle and string functions needle, haystack?
Its because PHP was designed, by many different people, over a long period of time, and with no strict standards in place at the time.
Original Answer:
You must make sure you set the variable inside the array to a reference as well.
Try this and take note of the array(&$t) part:
function test(&$t) {
$t++;
echo '$t is '.$t.' inside function'.PHP_EOL;
}
$t = 0;
echo '$t is '.$t.' in global scope'.PHP_EOL;
test($t);
$t++;
echo '$t is '.$t.' in global scope'.PHP_EOL;
call_user_func_array('test', array(&$t));
$t++;
echo '$t is '.$t.' in global scope'.PHP_EOL;
Should output:
$t is 0 in global scope
$t is 1 inside function
$t is 2 in global scope
$t is 3 inside function
$t is 4 in global scope
Another possible way - the by-reference syntax stays the 'right' way:
$data = 'some data';
$func = 'more';
$func($more);
function more(&$data) {
// Do something with $data here...
}
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.
Hey there, quick question here. I'm sure there's a simple answer.
Coming from PHP, I'm used to declaring a function with a default argument value like this:
function myFunction ($array, $sort = FALSE) {
}
I the sort parameter wasn't filled, the function would continue with the default value of false. In Obj-C, is there a similar thing?
I'm working through the exercises in my "Programming In Objective-C 2.0" book, and it wants me to re-write a fraction class print function to default-ly not reduce the fraction, but if the value TRUE for reduce is given, go ahead and reduce the fraction, then print. The chapter (Nor nowhere in the book) gives any information on this.
Thanks for your help guys :D
Default arguments don't exist in Objective-C, per se. They can't really, because the argument count is inextricably tied to the method name — each colon corresponds to one argument.
Objective-C programmers accomplish a similar goal, though, by creating "convenience" methods that just call to a more "primitive" method with some of the arguments filled in with default values. For example, -[NSArray indexOfObject:] could be implemented as version of -[NSArray indexOfObject:inRange:] with an argument of NSMakeRange(0, [self count]) for the inRange: part.
In this case, though, I don't think your book is talking about that. I think it simply means to reduce the fraction if YES is given for the reduce: argument and not reduce it if NO is given.
There are two standard patterns for achieving what you want.
(1) write a many argument form of a method and then provide fewer argument convenience versions. For example, consider the following methods on NSString:
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
range:(NSRange)compareRange;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
range:(NSRange)compareRange locale:(id)locale;
The first three are conceptually [and likely concretely, I didn't check] implemented as calls through to the fourth version. That, is -compare: calls -compare:options:range:locale: with appropriate default values for the three additional arguments.
(2) The other pattern is to implement the many argument version of the method and provide default values when an argument is NULL/nil or set to some value that indicates the default is desired. NSData has methods that are implemented with this pattern. For example:
+ (id)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask
error:(NSError **)errorPtr;
If you pass 0 for the readOptionsMask argument, the NSData will read the contents of the file using an internally defined default configuration. That default configuration may change over time.
This question is super old, but in case anyone finds it, the Objective-C version of the PHP code (assuming this is inside a class) would probably be something like this:
-(id)myFunction:(NSArray*)array {
return [self myFunction:array withSort:FALSE];
}
-(id)myFunction:(NSArray*)array withSort:(BOOL)useSort {
// CODE
}
I used (id)s as there is no data type information in your PHP code. Replacing the (id)s with actual data types would be wise.
Terrible necro but for anyone googling this, Xcode 4.5 supports (via Clang) overloading of C functions with __attribute__((overloadable)).
Overloaded functions are allowed to have different numbers of arguments, so if C functions are appropriate for what you're trying to do you can use that to get default argument values.
Here's a contrived example of an .h file with two functions, both called PrintNum:
// Prints a number in the decimal base
__attribute__((overloadable)) extern void PrintNum(NSNumber *number);
// Prints a number in the specified base
__attribute__((overloadable)) extern void PrintNum(NSNumber *number, NSUInteger base);
and in the .m file:
__attribute__((overloadable))
void PrintNum(NSNumber *number) {
PrintNum(number, 10);
}
__attribute__((overloadable))
void PrintNum(NSNumber *number, NSUInteger base) {
// ...
}
Note that the attribute must be specified in all definitions and declarations of the function.
No, default arguments are a feature of C++, not C or Objective-C.
What you would have to do in objective-c is the following (using your psuedo code above):
function myFunction ($array, $sort)
function myFunction ($array)
// call myFunction($array, FALSE)
You can easily achieve the same effect using #define.
The function in your header file:
+(NSDate*)getDateFromYear:(NSUInteger)year month:(NSUInteger)month day:(NSUInteger)day;
Add a #define for parameter function in header file:
#define GetDateFromYearOnly(year) [YourClassName getDateFromYear:year month:1 day:1]
Then your can use the function like:
NSDate* 2015Date = GetDateFromYearOnly(2015);
And you will get an NSDate object with date 2015/01/01.
If the function is not static, build a new function like this:
-(NSDate*)GetDateFromYearOnly:(NSUInteger)year;
And call:
[self getDateFromYear:year month:1 day:1]