Imagine you have just been handed an existing web site to do some upgrades. You are tasked with modifying some dialog style interfaces on the site and adding some new fields to the user form. As you start to scour through the server side code and the front end html you finally dig up an onclick event something like createDialogInterfaceForm(this) bound to an HTML element. Great you say, now you start digging through all of the JS looking for this magical function that you have found appears all over the site. When you finally find it you discover it and it has a tonne of internal branches based on the caller which then call other functions. Great you say, this function is used all over the place so making any modifications will result in me having to retest everywhere, so much for an easy fix. Now imagine instead, you see something like site.ui.dialog.user and to your astonishment there is only one single JS file for the site. Hmm, you say cool. So upon opening the single JS file you are presented with the following:
So what does a singleton provide you:
- Elegence in code
- Greater maintainability
- More obvious method calls
- A clear object structure that reflects the site structure in many cases
You may be saying at this point that this may be cool but wouldn’t I just end up with a massive single piece of code and even code that I do not need for a specific page. Well you would be correct in that assertion. So in the next post I will discuss how to separate your singleton code out into individual class files and load on demand into the master singleton.