Keep code in functions

This article is based on the ServiceNow documentation article. See the original article on the ServiceNow doc site: Keep code in functions

By default, an advanced Business Rule will wrap your code in a function, and it is important that this guideline is followed. When code is not enclosed in a function, variables and other objects are available to all other server-side scripts. This availability can lead to unexpected consequences that are difficult to troubleshoot. Consider this example:

var gr = new GlideRecord('incident');

gr.addQuery('active', true);

while ( {
   // do some processing here

Because the gr object is not enclosed in a function, all server-side scripts, including script includes and other Business Rules, have access to it. Other scripts may also use the common GlideRecord variable name gr. The duplicate names can conflict and lead to unexpected results. These issues are very difficult to isolate and resolve because typical debugging methods identify the Business Rule giving erroneous results rather than the Business Rule containing global variables. To avoid this issue, keep the default function with the same code snippet:

(function executeRule(current, previous /*null when async*/) {
    var grInc = new GlideRecord('incident');
    grInc.addQuery('active', true);
    while ( {
        // do some processing here
})(current, previous);

This solution is safer because the scope of the variable grInc is limited to the Business Rule since it is wrapped in the default function. If every script was wrapped, it would not matter what the variables were called. But it is good defensive coding to minimize the possibility of collisions even further, and avoid using a variable called gr at all. This makes the possibility of namespace conflicts even more remote.

Last modified on Jun 15, 2020