Why convert parameters to local variables in a function? - language-agnostic

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.

Related

Naming parameters the same as the variable passed to them?

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.

Is there a specific name for a function that takes its output as input and does that parameter have a name?

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

Should functions always return something (Javascript)

Should functions always return something? I often write very basic functions which are used as shorthand to do things that happen a lot such as:
function formsAway() {
$("#login_form, #booking_form").slideUp();
}
Should this function exist - is there a better way, or is this fine?
They don't have to return anything. If you leave it blank it simply returns 'undefined' which in this case is fine because you never intend to use the return value. The Javascript syntax is pretty simplistic and as far as I know there just isn't any real distinction between functions that do and functions that don't return a value (other than the 'return' keyword)
All JavaScript functions return something. If an explicit return is omitted, undefined is returned automatically instead. When a function returns, its instance is wiped out from memory, which also frees all the variables in its scope to be wiped out if nothing else points to them. Without a forced return memory management would have to be done manually.
To my knowledge, unless you need it to return something, a function doesn't have to return anything.
It may be different in other languages, but I've never heard it being necessary or good practice in JavaScript.
Should functions always return
something?
I believe that totally depends on the usage of the function.
is there a better way, or is this
fine?
IMO writing these kind of functions is good when there are many occurrences of the reusable code which can be replaced by the function so that the code looks much cleaner. But only for a couple of occurrences you may just put the code as it is instead of replacing it with function. You should also take into account the chances of reuse of this function in other places in future.

What's a good naming convention for methods that take conditional action?

Let's say I have a method, Foo(). There are only certain times when Foo() is appropriate, as determined by the method ShouldFooNow(). However, there are many times when the program must consider if Foo() is appropriate at this time. So instead of writing:
if ShouldFooNow():
Foo()
everywhere, I just make that into one function:
def __name():
if ShouldFooNow():
Foo()
What would be a good name for this method? I'm having a hard time coming up with a good convention. IfNecessaryFoo() is awkward, particularly if Foo() has a longer name. DoFooIfShould()? Even more awkward.
What would be a better name style?
I think you're pretty close. Put the action/intent at the head of the method name, for easier alphabetic searching. If I were writing something like that, I'd consider
FooIfNecessary()
FooIfRequired()
Say, for instance,
ElevatePermissionsIfNecessary()
You could use EnsureFoo().
For example, the method EnsurePermissions() will take the appropriate action if needed. If the permissions are already correct, the method won't do anything.
I've recently started using the convention:
FooIf(args, bool);
Where args are any arguments that the method takes and bool is either expecting a boolean value or a Func of some kind that resolves to a boolean. Then, within that method, I check the bool and run the logic. Keeps such assertions down to one line and looks clean to me.
Example in my C# code for logging:
public void WarnIf<T>(T value, string message, Func<T, bool> isTrue)
{
if (isTrue(value)) _log.Warn(message);
}
Then I would call it with something like:
WarnIf(someObject, "This is a warning message to be logged.", s => s.SomeCondition == true);
(That caller may not be correct, but you get the idea... I don't have the code in front of me right now.)
Michael Petrotta's answer (IfNecessary or IfRequired suffix) is good, but I prefer a shorter alternative: IfNeeded.
ElevatePermissionsIfNeeded()
And if you want something even shorter I would consider a prefix like May or Might:
MayElevatePermissions()
MightElevatePermissions()
I don't see what's wrong with the original code:
if shouldFoo():
Foo();
is perfectly clear IMHO.
Not just that, but it clearly separates concerns of deciding about doing the action, vs the action itself.
Another option for a similar question with a slightly different approach to avoiding the postfix:
https://softwareengineering.stackexchange.com/a/161754/262009

Is it good practice to name variables differently when defining more than one function?

For example, in this simple function where fun1 takes as input two numbers, adds them together and passes them to function 2 for printing the output. var1_in is local to each function, so is it OK to use the name var1_in in both functions, or is it better practice to call them different things?
fun1 <- function (var1_in, var2_in) {
var3 = var1_in + var2_in
fun2(var3)
}
fun2 <- function (var1_in) {
var4 = var1_in
print(var4)
}
As long as the functions are short enough to easily understand, then identifying the scope of local variables and parameters will be easy as well. But there isn't a hard and fast rule for this. What's important is that the code is easy to understand and that the names of variables are relevant and meaningful regardless if this means name duplication. Modern IDE's will also help here by highlighting the instances of such variables making it easy to see their declaration and various usage points. Point being, I would focus more on quality and meaningful naming rather than duplication of variable names.
EDIT - Of course, one situation to avoid would be naming a local variable or parameter the same as a global variable. This can confuse things greatly and lead to many a subtle bug.