Home > Blockchain >  Callback functions vs hardcoding inner function?
Callback functions vs hardcoding inner function?

Time:01-29

I'm reading about Callback functions in Javascript, and W3 schools reports that a callback is simply where a one function calls another, the latter of which is an argument that's passed to the first in the form of:


const callback = () => {
    console.log('callback executed.');
};

const myFunc = (callbackFunc) => {
    console.log('myFunc started')
    callbackFunc();
};

myFunc(callback);

My question is, in practice, how is this any different than hardcoding the callback into MyFunc's definition? eg

const myFunc = () => {
    console.log('myFunc started')
    callback();
};

I've heard callback functions mentioned in the same breath as async; so my best intuition is that this design allows the exact function, to be passed as an argument to myFunc, to be decided dynamically based on some logic external to myFunc.

However, I'd like confirmation/clarification and amplifying details.

CodePudding user response:

Your intuition is correct but the benefit and the use of it is tremendously big. That's allow Separation of Concern and Dependency Inversion.

And the fact we can pass function as any other value and return value (it's what we called high-order function) allow us to process composition of it.

Then we can code in purely functional way without the need of class to handle some state which is an Object Oriented Way. Both paradigm can be handle in JS because it's a multi-paradigm programming language but be aware of what we do is essential to not transform the code in a entire mess.

When you will study Promise you will see how to take advantage of callback to handle side-effect in a really canny way such we can manage side-effect and push it aside to keep reasonning in a more mathematical way. For instance imagine:

const callHttp = (callback) => {
    const res = // do asynchronuous operation taking time 
    callback(res);
};

You can dynamically pass down the result to handle it only after the delay execution to get the info. In such way you can program in a really neat way to manage side-effect of any types of event.

Enjoy your path through Javascript ;)

CodePudding user response:

Let's say we're building this web app that lets users upload images and then we can apply all sorts of image processing effects on them, like turning them into grayscale, sepia or even sharpening them.

Initially, we thought of just creating a function called "applyEffect" that takes in the image and a string representing the desired effect. But, as we started adding more effects, we realized that the switch statement inside the function was becoming a nightmare to maintain. Plus, every time we wanted to add a new effect, we had to go back and modify the "applyEffect" function.

function applyEffect(img, effect) {
    switch (effect) {
        case "grayscale":
            applyGrayscale(img);
            break;
        case "sepia":
            applySepia(img);
            break;
        case "sharpen":
            applySharpen(img);
            break;
        // etc.
    }
}

Now, let's try to solve it with a separate callback functions for each effect, like "applyGrayscale", "applySepia" and "applySharpness". Then, we created a new function called "applyEffect", that takes in an image and a callback function as arguments.

function applyEffect(img, callback) {
    callback(img);
}

Now, whenever we want to apply an effect to an image, we just call "applyEffect" and pass in the image, along with the appropriate callback function. It's way more flexible and easy to maintain.

applyEffect(myImage, applyGrayscale);
applyEffect(myImage, applySepia);
applyEffect(myImage, applySharpen);

By using callback functions, the applyEffect function is closed for modification (no need to change the applyEffect function when adding new effects) and open for extension (easily add new effects by creating new callback functions and passing them to applyEffect).

This is one of the SOLID principles for writing maintainable and scalable code.

  • Related