Suppose we have a JavaScript application with a large number of widgets. Consider the example caps. The initHeader() function collects all the DOM objects necessary for further work inside the header, adds event handlers, generally prepares for its use. Does the following code pattern "good tone" code writing?
function initHeader(){ // объекты виджета, с которыми будем работать в функциях var var1 = $('#div1'); var var2 = $('#div2'); // ... // вспомогательные функции function function1(){ // ... } function function2(){ // ... } function function3(){ // ... } } The peculiarity of this template is that all auxiliary functions are inside the main one.
Why such a structure? According to Robert Martin’s book Clean Code, ideally the function should have no arguments at all, and if the arguments are unavoidable, then there should be one, maximum two arguments. But in our case, inside auxiliary functions, you may need a large number of variables: jQuery objects, some constants, working variables like animation time, some entered data, and so on. If you write all the auxiliary functions outside the main one, then you will have to pass all this in the form of arguments, and you’ll hardly manage to get into two arguments. This structure, which I showed, eliminates the need to pass arguments, while all variables, being declared inside initHeader() , are not available outside of this function.
The second advantage of this approach is that it allows you to collect all DOM objects jQeury() through the jQeury() function, and then access them through variable names (if it is correctly called caching DOM elements, then you can say that this code template creates conditions to ensure caching of DOM elements).
And one more thing: it follows from the function name, but I’ll clarify that the initHeader() function itself is called only once (this can be done in the HTML code immediately after the closing </header> , for example), and internal functions can already be called as many times as you like
Please provide arguments for and / or against such an approach.
initHeader()function itself is executed only once, for example, it can be called after the HTML code of the header, then the function will be executed after the header is displayed in the browser. All auxiliary functions can be called at any time (an example of an auxiliary function is the search button handler in the header). - Bokov Gleb