It's a rather general purpose question and not specific to any one language. I don't quite understand the point behind passing a function as an argument to another function. I understand that if a function, say, foo1()
needs to use some result returned by another function foo2()
, why can't the values returned/updated by foo2()
be passed to foo1()
as is? Or in another scenario, why can't the foo2()
be called within foo1()
with its results being used therein?
Also what happens under the hood when a foo2()
is passed as an argument to foo1()
? Is foo2()
executed prior to foo1()
?
What's the point behind passing functions as arguments to other functions?
945 views Asked by dhanshreeA At
3
There are 3 answers
0
On
There are many reasons:
Dependency injection: if you pass a method that in production will use a database call, and you use it with different parameters, you could substitute it with some mock when unit testing.
Map, filter, reduce: you could apply the same method to a list of parameters, to map it, filter it or reduce it.
0
On
Usually to provide callbacks, or to separate interface from implementation. Look up the following:
-
1. Dependency Injection,
2. Callbacks,
3. Anonymous Functions (aka Lambdas),
4. PIMPL
etc
Take a look at this book where it is used extensively in developing TDD with C: https://www.amazon.co.uk/Driven-Development-Embedded-Pragmatic-Programmers/dp/193435662X
Generally speaking, you pass a function
foo2
to a functionfoo1
in cases where multiple evaluations offoo2
will be necessary - and you perhaps don't know in advance what parameters will be used for each call offoo2
, so you couldn't possibly perform the calls yourself in advance.I think that a
sort()
function/method on lists might be the best concrete example. Consider a list of People - you might reasonably want to sort them alphabetically by name, or numerically by age, or by geographical distance from a given point, or many other possible orders. It would hardly be practical to include every such ordering as built-in options tosort()
: the usual approach taken by languages is to allow the caller to provide a function as a parameter, that defines the ordering between items of the list.