programacion-referencias-a-funciones

What are and how to use Function References

  • 6 min

A REFERENCE to a function is a type of data that, instead of simply containing data, contains a link to a specific function in memory.

At first, the concept might be surprising because when you start programming you get used to having variables with data on one side, and functions that manipulate them on the other.

But when we talked about variables, we said that a variable is “a box” that could contain different things. Or as Peter Griffin would say… “a box can have anything… even a boat!”

Now, this includes containing functions, not just data.

referencia-funciones

A variable that contains a function

What are the advantages of being able to assign a function to a variable? That now we can treat a function as an object that can be assigned, passed as an argument, returned as a result, or stored in a data structure.

Don’t worry if “you find it a bit tricky to grasp”. But it’s a very powerful technique that allows us to separate the implementation of the function from its alias for invocation, which facilitates code reuse and the creation of modular code.

Function References

Let’s translate what we’ve said into some code (don’t worry too much about the syntax, we’ll see concrete examples later. For now, it’s just an excuse to understand each other).

What I was saying is that we are normally used to having,

  • Variables that contain data like my_variable which contains 10
  • Functions, like DoSomething, that perform actions

That is, something like this,

// a variable with data
const my_variable = 10

// a function
function DoSomething()
{
}

DoSomething() // invoke the function
Copied!

Now let’s see how to combine both things, a variable that contains a REFERENCE to the function. In this case, it would look something like this,

// a function
function DoSomething()
{
}

// a variable that contains a function
const my_variable = DoSomething;

my_variable() // invoke a function through the variable
Copied!

Instead of calling the function by its original name, we can use our REFERENCE to the function to invoke it.

Important, we must be careful and differentiate between assigning and invoking the function. For example, in the following case, observe the difference between assigning the function and invoking the function.

// this assigns the function to the variable
var my_variable = DoSomething;

// this invokes the function and assigns the result to the variable
var my_variable = DoSomething();
Copied!

The way to invoke the function will depend on the language we are using. In general it is (). But in any case the concepts are the same. Next, we see concrete implementation cases in languages.

Examples of function references in different languages

Let’s see an example of how to make a reference to a function in different languages. For the example, we’ll create a sum function that takes two parameters a and b and returns the sum.

Then we’ll create a variable sum_function that contains a reference to the function. Then we invoke this function through the variable, instead of using its name.

This is how this example would look in different programming languages.

C# has the concept of delegate, which is a Function Reference system.

// Definition of the sum function
int Sum(int a, int b)
{
	return a + b;
}

void Main(string[] args)
{
	// Assigning the function to a delegate
	Func<int, int, int> sum_function = Sum;

	// Invoking the function through the delegate
	Console.WriteLine(sum_function(3, 4)); // Prints: 7
}
Copied!

In C++ there is the concept of pointer, which allows establishing Function References.

// Definition of the sum function
int sum(int a, int b) {
    return a + b;
}

int main() {
    // Assigning the function to a function pointer
    int (*sum_function)(int, int) = sum;

    // Invoking the function through the pointer
    std::cout << sum_function(3, 4) << std::endl; // Prints: 7
}
Copied!

JavaScript is a dynamically typed language. Of course, it’s possible to use variables to contain other functions. In fact, it’s very common in this language.

// Definition of the sum function
function sum(a, b) {
    return a + b;
}

// Assigning the function to a variable
const sum_function = sum;

// Invoking the function through the variable
console.log(sum_function(3, 4)); // Prints: 7
Copied!

Finally, Python also supports Function References. In this case, you don’t even need to declare the variable, just assign the function.

# Definition of the sum function
def sum(a, b):
    return a + b

# Assigning the function to a variable
sum_function = sum

# Invoking the function through the variable
print(sum_function(3, 4)) # Prints: 7
Copied!

As we can see, apart from syntax differences, the concepts and even the usage are basically identical.

Internal Operation Advanced

The operation of function references is implemented in different ways depending on the programming language. However, broadly speaking, we can give a common explanation of how they work.

When a function is defined in a programming language, its code is stored in a specific memory location. This location is identified by a unique memory address.

A function reference is simply a type of data that contains this memory address. When we pass a function as a reference to another function or store it in a variable, what we are really doing is storing this memory address.

referencia-funcion-interno

When we use a function reference to invoke the referenced function, the program accesses the memory address stored in the reference and executes the code stored at that location.

Furthermore, this allows the program to dynamically invoke the referenced function at runtime, which provides flexibility and dynamism to the code.

Actually, if you think about it, it’s nothing more than a GO-TO. But supercharged, and much more controlled and secure.