Avoid unnecessary function indirection

Afiz Momin
2 min readDec 24, 2020

--

When a function calls two or more functions and processes each output before sending it over to the next, essentially you are composing logic. When a complex logic becomes difficult to manage and read, one may choose to break it down into smaller functions and call them from the main function. I have seen in the code base of the developers where a function merely does little to nothing before calling the function and returning an output. Makes me wonder is there a need for a function accepting arguments and merely passing to another function?

Why would a person do something like that? Is there a real advantage?

Let’s take a look at an example of function indirection. Suppose we want to render products with categories on the page and display the first name of a user. We created the helper functions that return the needed information to render on the page. To achieve this, we are directing our execution of logic and the reading order from the OnPageLoad function to these helper functions. Each of the function is just a wrapper doing as little as preprocessing the input and returning the response. Do we at all need them?

We don’t. So how we can improve our code so that while reading the flow of execution a reader does not have to jump between the lines in the modules and keep scrolling up and down forcing us to spend time on a worthless exercise.

So what are we missing here? It is not treating a function as a first-class citizen of the language is the actual problem here. Not all the language support functions as first-class, but Javascript does.

What does a first-class citizen mean? Is there a second-class citizen? Nah, it is just a metaphor.

A function in Javascript is an object and when it is assigned to a variable, the variable carries the reference to wherever it is passed or could be invoked later, did you forgot callbacks? When you have an opportunity to make the codebase readable and light you should. The more the lines of code, the more is the surface area for the bugs. Keep in mind!

As you can see the equivalent line of code below each function shows how to treat functions as first-class citizens which removes unnecessary indirection. After this refactoring, do you need these helper functions at all? You don’t unless you want to rename the function name. The implementation in OnPageLoad doesn’t change at all.

--

--

No responses yet