The Zurich release has arrived! Interested in new features and functionalities? Click here for more

sabell2012
Mega Sage
Mega Sage

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

____________________________________________________________________________

Original Article: Community Code Snippets:  Code Formatting (October 2015)

 

“If it was hard to write; it should be hard to read!” That was my alternate title to this revisit article!

Next to a lack of comments, script formatting is one of the most ubiquitous problems to be found with custom development on the ServiceNow platform. Sadly, it is usually associated with lazy or poor coding habits. Come on coders, please clean up after yourself! These are probably the same kind of people that put their used chewing gum on the top of park benches for other people to sit in!

If you find yourself fixing up someone else’s mess then, at the very least, click the format button. Formatting does NOT change the script itself; just makes it easier to maintain. 

Lack of formatting can be a potentially serious issue, and I have seen it lead to some bad mistakes. Here I will cover some of what I consider best practices in script formatting.

Formatting 101

So, what have I found? Here is a common one: Slapped together code. Well, it looks slapped together, doesn’t it? I found this out in the wild:

   if (isLoading ) {
      return;
   }
var opened=g_form.  getValue(‘opened_behalf’);
     if(opened==‘‘)
           g_form.  setValue(‘opened_behalf_eid’,’’);
           var lead = g_form.  getValue(‘u_lead’);

 

Solution:

So, if it hasn’t made itself clear; as to what the problem is: you can hardly read it let alone maintain it. No comments or brackets either. The code looks as if the “var lead” line is part of the “if”.   

Axiom: Properly formatted and indented code is the first step toward maintainability. 

Steps to fix it up:

1. Click on the Format button in the ServiceNow editor. Sometimes this does not work correctly so you will need to revert to step two.

find_real_file.png

2. Copy the script from the ServiceNow editor and paste into your favorite code editor (example: Notepad++), format the code, then copy it from that editor and replace the original code in ServiceNow. Simple stuff.

 find_real_file.png

After – how it should look (with brackets, spaces and blank lines added/removed to improve clarity):

if (isLoading) {
    return;
}

var opened=g_form.  getValue(‘opened_behalf’);
if (opened==‘‘){
	g_form.  setValue(‘opened_behalf_eid’,’’);
}

var lead = g_form.  getValue(‘u_lead’);

 

Indentation

Indentation allows a coder to quickly see variable relationships, variable scoping, function placement, open and closed brackets placement, and … well you get the idea. It vastly improves readability. 

The ServiceNow editor forces the indent to 4 spaces (nothing in the editor is configurable – one of the foibles I spoke of earlier). 

Here is one I made up, but before you ask, yes, I have seen this type of stuff in real life a lot of times!

Example 1: The Bad

var results = getResults();
function getResults() {
var incidents = new GlideRecord('incidents');
incidents.query();
while(incidents.next()){
gs.info(incident.number+'');
if (incident.number=='INC0000012')
break;
if(incident.number=='INC0000012')
gs.info('hello world');
}
}

 

Example 2: Ugly

And I see things like this as well!

var results = getResults();
function getResults() {
var incidents = new GlideRecord('incidents');
incidents.query();
while(incidents.next()){
    gs.info(incident.number+'');
    if (incident.number=='INC0000012')
    break;
    if(incident.number=='INC0000012')
    gs.info('hello world');
    }}}

 

Example 3: Properly indented code

Add brackets! Add blank lines!

var results = getResults();

function getResults() {
      var incidents = new GlideRecord('incidents');
      incidents.query();

      while (incidents.next()) {
            gs.info(incident.number + '');

            // brackets even around one line improve readability
            // AND allow for easier insertion of debugging statements. 
            if (incident.number=='INC0000012') {
                break;
            }
 
            if (incident.number=='INC0000012') {
                gs info('hello world');
            }
      }
}

Formatted you can see the hierarchy of the code. Again, put blank lines and whitespace where it makes sense to improve readability. I have had bugs literally leap off the screen after formatting and fixing up the indentation of a script!

Axiom: Adding brackets and whitespace improves readability and maintenance of code. 

The Script Editor

Several things about the editor got better recently. A lot better actually!

Editor Quirk 1:   Comments Can Cause Bad Formatting – FIXED!

It used to be that in some cases the format button got confused when code was commented out. This appears to have been fixed (not sure in what version, but it was mostly bullet proof). A couple of years ago @Matteo found that it also choked on JSDoc Format for comment on functions. This appears to have been corrected as well! It no longer does this after hitting the format button (note the indent under the //if:

find_real_file.png

Nor this anymore (thanks @Matteo for the example):

find_real_file.png

 

Editor Quirk 2:   Switch statement causes bad formatting – FIXED!

Another foible: switch statements would have their indentation removed. Used to simply drive me crazy. You will be happy to know that this has been corrected! So it no longer does this:

find_real_file.png

Spaces vs. Tabs – This is a non-error, ignore it

This one is still there. In some cases, your editor will throw a warning about mixed spaces and tabs. Ignore these. They have zero impact on the execution of your code and are simply annoying to obsessive compulsive people like me.

find_real_file.png 

Conclusion

Formatting is a best practice in any custom script development. Always keep in mind that you are probably not the only one that will be maintaining your code. Don't leave a mess. Good formatting habits are worth cultivating and making a personal standard (as well as a corporate standard). Use the editor format button as much as possible. Don’t leave your dirty socks on the floor for someone else to pick up. Ugh!

By-the-way formatting is not picked up by ServiceNow’s Healthcheck tool. So, it is up to you to do it right.

In my next article I will continue to tackle formatting issues in scripts. Believe-it-or-not there is more to this topic!

Steven Bell 

If you find this article helps you, don't forget to log in and mark it as "helpful" and bookmark it!

Also, if you are not already, I would like to encourage you to become a member of our blog!

You can find a comprehensive list of my community articles and videos here:
Community Code Snippets: Articles List to Date

 find_real_file.png

1 Comment