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”.