I'm currently building out some functionality on a page. When writing JS I've been making a set of smaller functions like FindCarouselLocations(elem)
, GetImagesFromLibrary(url)
, and BuildCarousels(images, locs)
which all use a subset of functionalities found in my global JS file.
When designing a page that's fairly heavily JS-reliant, does it make sense to have a single function that tells a story through other function calls? With the example functions above I'd make:
// previous function definitions...
function AddImageCarousels (){
var imageLibraryUrl = 'http://mysite.com';
var parentElem = document.querySelectorAll('.image-carousel');
var images = GetImagesFromLibrary(imageLibraryUrl);
var locs = FindCarouselLocations(parentElem);
BuildCarousels(images, locs);
}
document.addEventListener('DOMContentLoaded', AddImageCarousels, false);
Which I think tells a story on what happens when the page loads. I could alternatively remove some abstraction but would then have to start adding more comments or refactor another way. I, personally, think this creates a bit of self-documentation but I'm fairly new to development practices...
If I had a lot of things going on in the page, I'd even take one final step further and make a function that could look like this:
// previous function definitions...
function AddImageCarousels(){ /* */ }
function BuildPage () {
AddImageCarousels();
AddChatbot();
AddMaintenanceNotification();
}
document.addEventListener('DOMContentLoaded', BuildPage, false);
Where each main functionality was defined by a single function, but those functions are built similar to the AddImageCarousels
function.
Is this good practice or a code smell that implies a need for better design? And if it does, then what would be a better alternative?
I prefer to keep production files into as few separate files as possible to reduce the number of HTTP calls, but each functionality is usually in its own development file and transpiled later into the same .js
.