‘Right first time’: 5 Steps to Quality Code in ServiceNow

Being happy with ServiceNow code that ‘works’ might be storing up problems for later

With deadlines pressing, getting ‘something that works’ out of the door can be tempting for the most conscientious of developers. After all, we’ve been told that we shouldn’t ‘let the great be the enemy of the good’, haven’t we? But taking the time to create well-written, clean code saves time and headaches later on, and is essential for maintenance, upgrades and keeping your ServiceNow instance bug-free.

Here are five steps to writing high-quality code that you can follow today:

1. Does your code smell?

The term Code Smell was coined by Kent Beck and Martin Fowler in their must-read 'Refactoring' book. Code Smells are not bugs...yet. A code smell describes code which is valid and on the face of it functions as expected but has the characteristics of poor design or the potential for errors.

“It is not enough for code to work.” - Robert C. Martin

You can think of code smells as symptoms of an illness in your code. If you can spot the code smells you can stop the illness and prevent future production issues and maintenance nightmares

Here are some common Code Smells to watch out for in ServiceNow.

Large Scripts

That 50 line business rule...yup it's too big. If it's more than 10 lines you need to take a closer look!

When you spot them it might be time to create a Script Include, but don't think you can just copy and paste in your spaghetti code. Break down your script into distinct methods, with each method having a clear responsibility.

Other code smells include:

Unused variables Did you mean to use them? Is it old code? Perhaps a bug? Clean it up and you'll have simpler code and less to maintain

Complex Function Cyclomatic Complexity is a measure of the complexity of a piece of code. It is calculated by computing the number of flows through a program. Complex code may perform poorly and can be difficult to test thoroughly as it contains many different possible paths of execution.

Useless catch clauses Catch clauses in try/catch blocks should not simply rethrow the exception. It has the same effect as not having the catch clause at all. You should do something useful in a catch clause or remove it altogether

2. Code Like You Speak

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”―Martin Fowler

When it comes to code readability is favored to brevity. (How many times does "var gr" appear in your code?)

Here's a simple example

function myFunc(gr, a){
   return (gr.email.isNil() ? a : a.push(gr.getValue('email'));
}

How long do you need to spend analyzing this small snippet to understand what’s going on? Any ideas what gr is referencing? Probably not without backtracking through the code or worse making a guess and risking a bug.

So why create a pain-point for yourself? If we code how we talk then we might rewrite it like so...

function addUserEmailToArray(userRecord, emailArray{
if(!userRecord.email.isNil())
        emailArray.push(userRecord.getValue('email'));
    
return emailArray;
 }

That's better. By using descriptive function and variable names we know we are fetching the user’s email and adding it to an array if it's not empty. We've replaced ternary operators with regular old if statements. Ternary operators have their place but when it comes to core business logic If statements generally improve readability.

So don't rely on comments to explain what code does. Let the code explain itself.

3. Ace Best practice

We recently published a blog post on the performance impacts of using best practice script rules vs not. The conclusion showed that best practice conventions, such as using GlideAggregate instead of getRowCount on the client-side, do give a noticeable improvement in performance.

There are many best practice rules that are specific to ServiceNow. Although at times there are justifiable reasons for not following some rules, we should be familiar with them and adhere to them when possible.

4. Code with Style

“ Code is like humor. When you have to explain it, it’s bad.” – Cory House

Coding conventions help maintainability and avoid potential pitfalls. When all your developers name variables, functions, and scripts using the same naming convention you improve the readability and understanding of code amongst your team.

Enforcing rules such as brackets around “if statement“ bodies avoid potential pitfalls like below:

if(!gs.nil(source.parent))
    current.parent = source.parent;
    current.name = current.name +' '+ parent.name;

No doubt this developer only meant to set the name when the source parent was not nil, but as they left off the enclosing brackets line 3 always gets executed leading to unwanted behavior.

5. Automate It

Thankfully there are tools out there that can help us identify bugs, adhere to best practice and enforce code standards.

logo-4.png

We recently launched vt:codeworks - an application which runs in your ServiceNow instance and can detect code bugs, code smells, best practice violations and much much more.

vt:codeworks is a powerful static code analysis engine which analyses the structure, complexity and logic of your code to identify coding bugs, performance issues and areas affecting maintainability.

It comes preloaded with over 200 rules to detect code smells and bugs and you can configure you own rules to enforce coding standards. It gives you feedback as you code and the exact fix to remediate any issues found – saving time and effort so you can focus on the difficult stuff!

Its available on the ServiceNow Store and you can find out more at www.vorto.co/codeworks

 
vt:codeworks in action

vt:codeworks in action