SBM MODSCRIPT, PART 15 - Singletons

As a common programming pattern, singletons are very helpful with data that needs to be read once and then reused throughout the program. This may not be required for simple scripts, but for long running, complicated scripts, this can help with keeping the script running with high performance. Since scripts often run as parts of transitions that users are clicking through, performance can affect user confidence and contentment.

To create a singleton in ModScript, follow the following pattern:

def GetConfiguration() {
  global g_appconfiguration;
  if ( g_appconfiguration.is_var_undef() ) {
    g_appconfiguration = Map();
    // read various configuration settings from DB or file system and inject into the map
  return g_appconfiguration;

Create a function. Inside the function, declare a global (but do not initialize it). Check if the global is undef, if so, initialize it and set it up. Finally, return the global. The global variable should have a very unique name, as it is global and we do not want it to interfere with other scoped variables. Since it is global, this means it will have the lifetime of the script, meaning the check for is_var_undef() will only be true the first time. As such, you can be confident that the time taken to read configuration data will only occur once, and can be accessed as often as needed throughout the script lifetime. 


SBM ModScript - Table of Contents

SBM MODSCRIPT, PART 14 - Checking the Type of a Va...
Allow a User Web Portal to Automatically Sign a Us...


No comments yet

Recent Tweets