What is hardcoding?
Hardcoding refers to the practice of embedding specific, fixed values directly into the source code of a program or script, instead of using variables or parameters. These hardcoded values are typically constants or literals that are explicitly written into the code.
Why is this an issue?
Hardcoding URLs in ServiceNow development can introduce significant challenges. Embedding specific URLs directly into the source code, instead of utilizing variables or parameters, gives rise to issues such as:
API Compatibility Issues: Hardcoding URLs can also lead to problems when APIs are updated or deprecated. If the hardcoded URL is an API endpoint that changes or becomes obsolete, the code will fail.
Deployment Complications: Hardcoded URLs can complicate the deployment process. If URLs differ between environments, the code will need to be modified for each deployment, increasing the risk of errors.
Increased Error-Proneness: Manually updating hardcoded URLs in multiple places can easily lead to mistakes, potentially breaking functionality or causing unintended redirections.
How do I fix it?
To address this issue, ServiceNow has empowered developers to store arbitrary values using System Properties. Utilizing System Properties encourages developers to use meaningful names that align with a given context. The initial step involves creating a System Property to store the URL, following these steps:
In the Filter Navigator, type and enter sys_properties.do.
Populate the fields accordingly:
- Name:
url_name
. - Description: "Add a description that will identify what you are accomplishing".
- Type: string.
- Value:
https://www.servicenow.com
(URL name).
- Name:
Double check if the fields are correct and Save.
After creating the new System Property, proceed to incorporate it into your code on the relevant record. While it is challenging to provide a universal example for every scenario, a best practice enforced by ServiceNow involves retrieving the property using the gs.getProperty()
method:
1
var getURL = gs.getProperty("url_name");
The example above works for the Server-Side, but since there is no gs
API in the Client-Side, there is an alternative way to get the System Property. A good way would be to apply the global object to store and retrieve values without making additional server calls:
1 2 3 4
g_scratchpad.getURL = gs.getProperty("url_name"); // Client Script g_form.setValue("instance", g_scratchpad.getURL);
It is worth noting that ServiceNow provides some out-of-the-box System Properties designed to handle URLs. For example, when attempting to retrieve your own instance URL, you can use the existing System Property named glide.servlet.uri
:
1 2
// Retrieving the instance URL using the existing system property 'glide.servlet.uri' var my_instance_url = gs.getProperty("glide.servlet.uri");