The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Jake Gillespie
Kilo Guru

As a ServiceNow Technical Architect, I often need to write code to perform complex functionality within the platform that cannot be achieved through the available configuration methods. In addition to this, I also see a lot of code written by other Administrators, Consultants and Developers etc. To say that this code varies in style and complexity would be quite the understatement. While it is understandable that not everyone thinks the same way, the problem is the inconsistency throughout the code, and a general lack of understanding or knowledge of the ServiceNow Technical Best Practices.

In this multi part blog series, I'll seek to identify and explain some of the ServiceNow Technical Best Practices, as well as my own tips for writing reliable and reusable code, not to mention why they are important to follow. This article will focus on scripting in general, so if you haven't studied software development before, or are simply new to scripting, then stay tuned!

Use consistent styling

First and foremost, code should be indented consistently. Much like reading a book, developers learn to read (and write) code by knowing how the control (program flow) will branch based on conditions or loops etc. If code is not indented consistently, it becomes very difficult to understand what the code is doing, and therefore how to successfully modify it. By using indentation, you can avoid having to count how many open or close curly braces there are, when identifying which IF or FOR block the current line of code falls within. Trust me, it's easier! And, considering that ServiceNow offers a "Format Code" function as part of the Script field toolbar, you really have no excuses.

Know your data types

Many programming languages are non-negotiable when it comes to assigning values to Variables defined as a specific type, otherwise known as "Type Safety". JavaScript however is not one of those languages. JavaScript is actually very flexible and adaptive, which is good and bad. The good side of this is that JavaScript will sometimes fix an issue that you may have overlooked. But, the bad side of this is that it promotes a lack of discipline when writing code. Worse yet, if the bug is missed during the testing cycle, it could be published into your production code. The first symptom of a problem relating to data types is usually when a comparison between two values produces an unexpected result. So, my advice is that if you know what type of data you wish to store and compare, then always define your Variables as known types (Strings can be defined as "", Numbers as 0, Boolean as true/false etc.). This principle should also be considered when writing functions that return values. Those values should match the data type of the Variable they're being assigned to. If in doubt, convert the return value to the type you require. In JavaScript, you can use String(value) to convert a value to String or Number(value) to convert to a Number. For Booleans, simply convert the value to a String first, then compare to "true". This will return Boolean true if the value is actually true, else it will return Boolean false. This is particularly handy when transferring values via XML (e.g. via GlideAjax, SOAP or REST).

Avoid non-descriptive names or Variables and function names

Avoid using Variables with extremely short names, as it becomes more difficult to understand the purpose of the variable throughout the code. Exceptions to this rule include using single letter Integers for iterating through loops (e.g. i), although it is still advisable to describe these variables with some detail (especially when you have multiple loops in the same function). In addition to this, you should also avoid using extremely long names. Try to find some middle ground and give your Variables a name with purpose.

Use Objects

JavaScript might not be a full Class-based Object Oriented programming language, however it is Object-Oriented, so be sure to make full use of Objects. For those new to Objects, these are basically Variables with more Variables inside them. I often see code where separate Variables have been defined to store data that relates to the same entity (e.g. Information regarding a single user such as First Name, Last Name, Email etc.). It is far more efficient to store these values in an Object, which can easily be passed between functions. Objects can even be pushed into Arrays! If you need to convert an Object or Array to String format (a common practice when transferring data via AJAX, SOAP or REST, you can convert to JSON format. JSON is great because it will preserve your variables in their native JavaScript data types.

Keep it simple

Some developers will often try to condense their code into a few lines as possible, believing that this is more efficient, and this is certainly the case in some programming languages. However, in my experience using the ServiceNow platform, a few extra lines of code used to define additional Variables won't make a huge difference. For example, often times you will need to evaluate a number of conditions before branching your code based on the outcome. In ServiceNow, this often involves dot walking from the "current" object or calling functions from the API to return a value. If you add all of these into the condition of an IF block, it can become messy and difficult to understand, let alone debug. For this reason I will often simplify the overall condition by first retrieving each component as a true/false value, and storing them as Boolean Variables. Then I use these Variables in the condition block. If you need to debug an issue, simply add some log statements to display the value of each of these components. For complex logical operations, it would be better to move the logical processing to it's own function, and have that function return the overall result to your IF block.

Error trapping and preventing crashes

There are many reasons why your code can fail/crash, or produce undesired results. A major cause of this is when the developer has not considered all of the possible scenarios from a logical and technical point of view. A simple example is processing input from a user. If the code is expecting a number but the user enters some text, how will it react? If the developer assumed the value would always be a number, and therefore did not allow for any exceptions, the code will likely fail. Simply put, a piece of code can be modified to allow exception cases to exist without crashing the code. This is generally referred to as "error trapping", where the goal is to handle any exception cases without causing the code to crash. A simple solution to the above scenario would be to detect the undesirable input value and report an error message back to the user, rather than letting the code continue running and potentially fail. This simple principle of checking whether a value is within the nominal range, or the expected data type, can make all the difference. This also applies to values returned by functions called by your own code.

Commenting

Last but not least, you should always comment your code. Comments not only tell other developers what your code does (or at least what it was intended to do), they also tell you what your code does. Unless you have an exceptional memory, remembering exactly what each line of code does in a function you wrote 12 months earlier will likely be a challenge. As a wise developer once said, be kind to your future self and comment your code. This is not to say that every line of code requires a comment, but I do suggest commenting the following:

    • Groups of Variables or Objects (a single line describing what each group is for)
    • Functions (describe in a few lines the purpose of the function and what arguments or return values it uses)
    • IF blocks or FOR loops (describe the purpose of each)

In this article we've covered some of the basic principles of scripting best practices. In my next article, I'll discuss Client Script Best Practices and how they apply specifically to ServiceNow. For further information on the topics covered in this article, please see the following pages:

NOTE: MY POSTINGS REFLECT MY OWN VIEWS AND DO NOT NECESSARILY REPRESENT THE VIEWS OF MY EMPLOYER.