top of page

Get the Most From Your Code: Reusability & Centralization

Updated: Sep 22, 2020



“I’ve done that before!” Most people who code have made this exclamation. What often follows is ctrl+C and ctrl+V of the same lines from one scripting file to another. In ServiceNow, this sometimes takes the form of navigating to a business rule or client script, changing the targets, and hitting “insert and stay”. Joyously the developer exclaims, “I’ve reused code!”


Well… sort of.


Code reuse is a time honored practice among programmers. Whether they’re recalling things they’ve written themselves or finding snippets others have published somewhere on the internet. The ServiceNow community is one of the most friendly and helpful professional groups I’ve ever had the privilege to be a part of. Contributors and participants in the community share their knowledge (and code) freely, helping each other look like superheroes to their respective organizations.


The question then becomes: What’s the “right” way to reuse code in ServiceNow?


It seems easy enough to simply copy and paste the same function into the various spots where that behavior is required. It works. No one can argue that. The challenge is maintenance and future enhancements to that code. If it’s been propagated to dozens of scripts across the platform, developers are obliged to find every instance and update it with the new version. This is tedious, and unreliable. Inevitably, some instance of the code is missed. Left to languish and fester, the un-updated code eventually rears its ugly head when you least expect it. Like the Hydra, you cut off one head by solving one issue, but then two more pop up in its place!


Okay, maybe it’s not that dramatic, but you get the point.


Updating copied code in multiple places is a pain, to say the least. Centralizing functions and making calls to them by name reference only really simplifies maintenance. When you need to update that central function, you only have one place to go to modify it as opposed to dozens. ServiceNow’s primary facility for doing this is “Script Includes”. ServiceNow advocates this practice and carries its torch by extensively using script includes in their out of the box feature sets. How do you use it? There’s plenty to google on this topic (including Steve Bell and Mark Amann’s 2018 CreatorCon session “Architecting Scoped Scripts: An Approach to Reusable Code in ServiceNow” Presentation & Lab), but I’ve provided a quick run down at the end of this article.


Script Include Setup

Each Script Include has a name with formatting enforced. The API name is “ApplicationScope.ScriptIncludeName”.




The API name is important to recognize when dealing with application scope. A script in one application scope must use the full API name of a Script Include residing in another application scope. If the script will be used for any client side work, the “Client callable” checkbox must be checked.


Server-side Script Includes start with an empty default “initialize” function whereas client callable script includes extend the AbstractAjaxProcessor script include. Functions written with this basic syntax:


functionName: function(params) {

//insert script here
return;
},

Server Side Calls

Business rules can utilize functions in a Script Include using the syntax:


//same application scope
var ourExample = new ScriptIncludeName(params).functionName(params);

//cross application scope
var ourExample = new ApplicationScope.ScriptIncludeName(params).functionName(params);

Server side functions in a Script Include can simply run an update action, or they can return usable data types such as strings, objects, and boolean. The business rule can then use the returned value to continue additional actions.


Script Includes can call other Script Includes! Following the same syntax as for business rules, a complex function can be simplified by utilizing other existing code as part of its behavior. Reuse for the win!


Client side

Client scripts call Script Includes to do server functions or data lookups using GlideAjax. One use case might be to look up additional values based on a selected user. The client script formats its GlideAjax like this:


var gaUserInfo = new GlideAjax('ScriptIncludeName'); // invokes GlideAjax and passes the name of the script include. Remember to include application scope if crossing scope boundary
gaUserInfo.addParam('sysparm_ourUser', ourUser); // send a parameter for use in the script include
gaUserInfo.getXML(ajaxCallback); // send the request and identify the client script function that will be used for callback processing

To protect the user experience, this is not done synchronously. The value is processed and sent back to the client script to be handled in a callback function. Callback functions follow syntax similar to the following:


functionajaxCallback(response) {
var answer = response.responseXML.documentElement.getAttribute("answer"); // pull out the actual return value
answer = JSON.parse(answer); // if appropriate use this to convert the string to an object
g_form.setValue('email', answer.email, answer.email); // use the value in the response to perform an action
}

It’s important to note that GlideAjax can only return string values. The Script Include could build an object, then use JSON.stringify() to turn it into a string to send back. The client script callback function will need to process the string once it receives the return value.


One more common client side use of Script Includes is in condition filters. Utilizing the format below you can call a Script Include that returns a comma separated string for a list lookup.



One of the best parts about using ServiceNow is the extremely welcoming community that comes with it. Through the community and other resources, developers have the opportunity to leverage openly shared code which can be the key to a successful customization. Getting the most from your code should always be a top priority and that is why reusability and centralization are critical weapons when developing in ServiceNow.


Interested in learning about ServiceNow Best Practices? See why the Best Practice Engine from Bravium Labs is the top rated app in the ServiceNow app store here.

330 views0 comments

Recent Posts

See All
bottom of page