Are there any rules (or will I run into any problems) if I name the parameters of a function the same as the variable I will pass into them?
For example in Python:
def foo(param):
pass
param = 2
foo(param)
In the fairly limited programming I've done, I have not ran into any problems doing this. Will I get problems in certain languages? Is this okay to do, or is it a practice to be avoided?
The "problem" in this particular case is that the function parameter name will shadow the outer param variable; i.e. you cannot (implicitly) refer to the global param anymore because inside your function param is defined as a local variable.
But, this is really as it should be. Your function should only worry about the parameters it declares locally, not about implicit global variables. Conversely, a caller of a function should not have to worry about anything that goes on inside a function. Naming a variable the same as a parameter to a function is of no consequence to the caller, and should be of no consequence to the function itself.
So, no, there's absolutely no issue here.
Related
I have a really basic question about something that I've never paid much attention to until now:
I noticed that when creating a function (in JS or Python) that uses a variable from the outer scope, the function is not defined using the value of the variable but rather the variable itself. So if I change the value of the variable the function will use the new value.
This is what I mean
let a = 10;
function printA(){
console.log(a);
}
printA(); // => 10
a = 20;
printA(); // => 20
a = 10
def printA():
print(a)
printA() # => 10
a = 20
printA() # => 20
I thought this was only going to work of objects because of the way you can modify an object inside a function but not primitive variables because there's no way to change their value without reasigning them. I guess this is a different story.
What I'm trying to understand is: when typing a variable name is typing its memory address what I'm really doing? Does this happen with all languages?
when I create a function like printA() that uses a variable that is not an argument, is the variable bound forever to the function by its address?
The variable a is "captured" by the function. The specifics of how that happens are usually implementation details and may result in the compiler/interpreter producing code that doesn't much resemble the original.
For instance, in C# (I know, not one of the languages you mentioned, but it's the one I'm most familiar with), the compiler will create a separate hidden class which actually contains fields for the variables that are captured by a lambda or nested function. It then accesses these fields rather than plain variables.
by its address
Variables don't typically have an address. For instance, every time you call a method, it will typically have an "activation record" of some kind created, that will typically contain its variables. But note that these records are not at some fixed location, which is how you can have parallel execution of methods, recursion, etc, without interference. (Some older BASICs did have fixed activation records, which is why they didn't allow for recursion). These activation records may typically be placed on some kind of stack.
But as I say, for captured variables, the compiler will typically need to do even more so that those variables aren't just stored in an activation record, and so that their lifetime is no longer tied to a single call.
True or False: When a function is called, the calling program suspends until
the function completes.
True or False: When you call a function with a list as a parameter, you could
change the original calling program’s list from within the function
True or False: When you call a function with a dictionary as a parameter, you could change the original calling program’s dictionary from within the
function.
Im very fuzzy on these questions and what they mean, could someone help explain these?
1.True
the original program will stop and going to run the function. It will back to the place where it stop and start to execute the next line command after function done.
2.False
call by value. it wont change the original variable's value.
3.True
call by pointer or call by reference.
Sometime yes and sometimes no. It depends whether you are calling it synchronously or asynchronously, see this answer for the distinction: Asynchronous vs synchronous execution, what does it really mean?
In most cases yes, because you are just passing by reference, i.e you are passing the location in memory of the param you are passing. However, you can also pass by value, i.e passing a copy of the object. See this question for more detail: What's the difference between passing by reference vs. passing by value?
same answer as your previous question. Whether you are passing an integer, string, array, list, dictionary, it doesn't matter, it all depends on whether you are passing by reference or by value. Which one of these happens by default depends on which programming language you use. You can determine which one is happening pretty easily with some experimentation: Define a function with a dictionary variable, add a key/value pair call another function with the dict as a param, and modify it in the called function, then print it out in the calling function once the called function has returned. If it has been modified, you know you are passing by reference. If it has the original key/value you set in the caller and is not modified, you know you are passing by value.
I'm a beginner and I remember reading somewhere, but unfortunately do not remember where, that it is good practice to first convert parameters of a function to local variables, before working with them. Could someone explain why?
void MyFunction(type param)
{
type myVar = param;
//do stuff with myVar instead of param
}
I'm guessing if param passed into MyFunction was a pointer then it might be possible the data that it's pointing to could change while MyFunction is being executed, but are there other reasons?
There is no reason to do the copy in any modern language that passes by value.
It would have been useful in older languages, like Algol, that pass parameters by name. See this example.
It's bad;; when type myVar = param;, type's copy constructor called. It's unnecessary unless you use both myVar and param for different purposes.
edit: If type's copy cost is almost free, It can be used for convenience and readability.
There are some answers to this question here. The answers why one would copy a value that has already been copied point mostly to maintainability considerations.
I work with a BASIC programming language and have found it useful to write functions that rely on their output as a parameter. Such as
inOut = someFunction(inOut)
I'd like to call this a recursive function. but it doesn't seem right because it is not calling itself. Can someone tell me what the name of this type of function is and if the parameter/return has a special name?
Thanks!!
This is an ordinary function as any other. The thing you show is called reassingment. You can rename inOut on the left with newinOut and it will not change anything... there is absolutely nothing special about the function, it's a naming pattern, that's all.
In many languages (including VB, but not sure about classic BASIC) there's something called passing parameter by reference. It's not exactly what you posted, but rather simple
someFunction(inOut)
parameter is passed into the function, changed there and the change persists outside the function
What is the advantage of having this/self/me pointer mandatory explicit?
According to OOP theory a method is supposed to operate mainly (only?) on member variables and method's arguments. Following this, it should be easier to refer to member variables than to external (from the object's side of view) variables... Explicit this makes it more verbose thus harder to refer to member variables than to external ones. This seems counter intuitive to me.
In addition to member variables and method parameters you also have local variables. One of the most important things about the object is its internal state. Explicit member variable dereferencing makes it very clear where you are referencing that state and where you are modifying that state.
For instance, if you have code like:
someMethod(some, parameters) {
... a segment of code
foo = 42;
... another segment of code
}
when quickly browsing through it, you have to have a mental model of the variables defined in the preceding segment to know if it's just a temporary variable or does it mutate the objects state. Whereas this.foo = 42 makes it obvious that the objects state is mutated. And if explicit dereferencing is exclusively used, you can be sure that the variable is temporary in the opposite case.
Shorter, well factored methods make it a bit less important, but still, long term understandability trumps a little convenience while writing the code.
You need it to pass the pointer/reference to the current object elsewhere or to protect against self-assignment in an assignment operator.
What if the arguments to a method have the same name as the member variables? Then you can use this.x = x for example. Where this.x is the member variable and x is the method argument.
That's just one (trivial) example.
I generally use this (in C++) only when I am writing the assignment operator or the copy constructor as it helps in clearly identifying the variables. Other place where I can think of using it is if your function parameter variable names are same as your member variable names or I want to kill my object using delete this.
Eg would be where member names are same as those passed to method
public void SetScreenTemplate(long screenTemplateID, string screenTemplateName, bool isDefault)
{
this.screenTemplateID = screenTemplateID;
this.screenTemplateName = screenTemplateName;
this.isDefault = isDefault;
}