When writing large amounts of recursive code (for valid reasons), I have come across many parameters that are not used in specific functions, but are still needed for a subset of all of the functions.
IE this situation (a, b & c are numbers):
function fun1(a, b, c) {
if(a > b) {
return fun2(a, b, c);
} else if(b > c) {
return fun3(a, b, c);
} else {
return a;
}
}
function fun2(a, b, c) {
return fun1(a + b, a - b, c);
}
function fun3(a, b, c) {
return fun1(a * c, b, a / c);
}
(I don't actually know if this terminates)
In this example, fun2
never actually uses c
, but it still has to require c
as a parameter. In fun3
, this is the same thing but for b
, and fun1
only cares about a
.
In this situation, what should be done to reduce the number of parameters down to only the parameters each function needs & not the parameters that get used in other functions?
(When I say not used
, I mean passed through)
Best Answer
You're contradicting yourself:
1
2
Passing a parameter counts as using it. You're thinking that it's unused because it just happens to call
fun1
, at a time whenfun1
also happens to be the method which calledfun2
in the first place.But that's not inherently the case.
fun2
could be usingADifferentMethod(c)
internallyfun2
could be called byAnotherCompletelyDifferentMethod()
In either of those cases, your assumption that
c
is "not used" does not stick.In this recursive structure, the parent
fun1
and the childfun1
should not be labeled as "the same function". They are not. They each have their own separate execution with their own separate scope.Just like how two separate objects of the same class type are not labeled as "the same object"; two method calls of the same method are not labeled as "the same method" (not in this sense you're trying to use, at least).