Use anonymous functions sparingly

This is the first of a bunch of posts I’m going to write on programming tips and best practices.

This one is about Anonymous functions ( a sometimes useful technique if your going to use in one place and throw away ). 

And thats all well and good, however these make code more difficult to understand ( especially large code bases you need to maintain ).

For example imagine some code you need to maintain, lets say it starts off with a long file you need to read through and get a high level understanding of. If its littered with anonymous functions it’s makes it hard to understand (quickly, quickly being the operative word, we’re busy people after all with lots of a new features the boss wants to add).

Is this easier to understand (approach 1)

        $(document).ready(function() {      
            
            
            console.log("add evy to view extra controls "); 
            var view_extra_controls = document.querySelector(".view_extra_controls"); // should only be one - lm 
            console.log(" button = "+view_extra_controls);         

            view_extra_controls.addEventListener("click", function (event) {
                
                var controls = document.querySelectorAll(".row_controls");

                controls.forEach((control) => {

                    console.log('conty = '+control);

                    //control.style.display = "none";

                    jQuery(control).toggle();
                });
                

            }, false);

 

Than this

        $(document).ready(function() {      
            
            
            console.log("add evy to view extra controls "); 
            var view_extra_controls = document.querySelector(".view_extra_controls"); // should only be one - lm 
            console.log(" button = "+view_extra_controls);         

            view_extra_controls.addEventListener("click", toggleDisplayOfControls );

 

It’s quicker and easier to read and understand the 2nd code ( we don’t even need to read the function ‘toggleDisplayOfControls’ because from its name it’s obvious what it does).

To take this one step further we can nicely comment the function (toggleDisplayOfControls) at the top ( as is standard ) if needed (in my experience anonymous functions are rarely commented).

        /*
         * when the user  clicks the link all the extra controls are shown or hidden
         */
        function toggleDisplayOfControls(){
            blach, blah
        }

 

Leave a Comment