Tag Archives: coding

ServiceNow Coding Style Part 2

So as a continuation to the previous article I want to expand the entire process of Coding Style with steps you can use in your own coding practices and as the basis of a Peer Code review process.

Step 0 – Installing Sublime (or another Smart Editor)

These instructions are set up for Sublime but are mostly tool agnostic as long as a similar plugin can be found.   This process will take a few minutes, but it will save you so much time I don’t think you will mind.  While it’s good to be aware of all the recommendations so you can use them naturally when you are coding, rely on tools as much as possible to automate code cleanup.

Grab Sublime from http://www.sublimetext.com/2 .  It’s $70 for a User License, but it’s worth every penny IMO.  You can evaluate it before you buy it to make sure it’s right for you.

Install the Sublime Package Control tool using the instructions from https://sublime.wbond.net/installation#st2.

Install node.js from http://nodejs.org/.  This is required for JSHint.

Install JSHint http://www.jshint.com/install/

Install the JSBeautify, DocBlocker, JSHint Sublime Plugins by opening Sublime and pressing Ctrl+Shift+P (Mac users figure this out on your own!) and typing “Package Control: Install Package”

When the Plugin window pops up start typing the name of the plugins, then press enter to install.

JSHint and JSBeautify both work on .js files, so to test create a test JS file with this content and press Ctrl+Alt+F to format it, and Ctrl+Alt+J to JSHint it.  If everything is installed correctly you should get a list of errors in the script.

function fakeFunction(name, cb, isBool) {
if(isBool==true){
cb(name)
}
Step 1 – Formatting

This refers back to the last post and is the first thing I usually look for in a code review.  Using JSBeautify makes this very simple, just run it, I accept most of the defaults, the only thing I might change is the indent_size setting to “4”.  All plugin settings can be tweaked in Sublime by going to Preferences > Package Settings > Package Name > Settings Default.  All changes should update immediately.

Step 2 – Naming Conventions

Avoiding poorly named variables, functions and records is essential to understanding code.  Properly named functions and variables make the code self-documenting and eliminate the need for many comments.  Here is a recap of the Coding Standards from the last article.

Variables – camelCase
Functions – camelCase
Private Functions – _camelCase
Classes – InitialsAreCapitals
Constants – ALL_CAPITALS
CSS Class – kebab-case
ServiceNow Records – PREFIX – Record Name
(for records that don’t use the name as a file name)
For UI Scripts it can be anything just no spaces.
For UI Macros I try to identify the usage like service_catalog_menu

Step 3 – JSHint Errors

JSHint will likely drive you insane with it’s complaining but it WILL make you a better coder and less dependent on JavaScript to ignore your mistakes.  To run it in Sublime you must save the file as .js

It will run automatically on Save or by pressing Ctrl+Alt+J

Certain things you can ignore are issues regarding using a function before it was defined, any complaints about ServiceNow specific objects not being declared (since they are global) and the error Do Not use JSON as a constructor.

Other than those exceptions I try to, and recommend you try to, fix all errors reported.  == versus === is very important to pay attention to because in MANY places === will break previously working functionality.  It is still best to use === and to explicitly compare types correctly or convert objects to strings before comparing.

It is most definitely more work NOW but it will save you headaches in the long run.

Step 4 – Engineering Principles

Two Principles that I mentioned before are DRY and SOC.  These should be applied when possible.  It is important to understand how to properly use ServiceNow to implement these principles.

Example – Within a series of business rules the same function is repeated and changed only slightly in each business rule.  The correct way to apply DRY in this case is to generalize the function so that the “tweaked” part is a parameter and then move that function to a Script Include.  It may even be possible at that point to move all the Business Rules to a single rule.

Example – Several reports were created as UI Pages that use the same basic layout but with just tweaked values.  In this case it may be best to either pass the parameters in the request OR to relocate the copied layout to a UI Macro and then include the macro.

Example – The same function is used within Client Scripts throughout the system.  In this case moving the function to a UI Script might be the best solution so the function is available to all Client Scripts.

The other principle I try to implement is Separation of Concerns.  This too goes back to understanding where all the code should be placed in ServiceNow.

Example – If styling is included directly in HTML  it is best to move that to a Style Sheet record and include that sheet.

Example – When working on a custom UI Page JavaScript to manipulate the DOM and make GlideRecord queries is mixed within functions.  This is definitely a bad way to do things, at the very least the code should be separated into functions whose intention is very specific.  At first glance, this may seem like just extra busy work, but the inevitably the application will grow, and if code is all separated by concern, it makes it easier to understand and re-use.

These principles are not hard rules, they need to be applied with some discretion.  If it is the 11th hour before a production push I would not recommend re-factoring all code into Script Includes.

Step 5 – ServiceNow Best Practices

This is a growing list of fixes or quirks within ServiceNow which just need to be memorized and looked for.  This list will update as I find and create more worst practices.

Do not use current.update() in onBefore Business Rules
Limit Synchronous GlideRecord Calls
Create functions in Business Rules and call them
Avoid nesting GlideRecords deeply
Don’t hardcode values; use Constants or System Properties
GlideRecords should check for next or hasNext before using them
All variables should be declared
A function should not be longer than one screen and ideally not even remotely that large
All paths in an AbstractAJAXProcessor Script Include should return a value
To get a GlideRecord field value, always use .toString() or .getDisplayValue()

Step 6 – Documentation

For all non-generated functions, like Client Scripts, I try to generate documentation.  This is not the same as comments, which should be used SPARINGLY.   Documentation states exactly what a function does, what it accepts as parameters and what it returns.  This is especially important in JavaScript because we don’t always know the type of parameters and returns.

To create a block like this, in your file right before a function you can type /** and enter.  This will automatically look at the function and pull out its parameters and returns and create the documentation for you.  I used an onChange function here for example but since they wont typically change parameters its not necessary to document each param, just the description.

/**

* Looks up the current caller and adds VIP styling
* and sets location based on the callers location
* @param {Object} control
* @param {String} oldValue
* @param {String} newValue
* @param {Boolean} isLoading
*/
function onChange(control, oldValue, newValue, isLoading) {
//…
}

If all of your code lives locally on your system, you will be able to create API documentation automatically with these blocks.

Local Files and Backup

I find it a best practice to store every file I work on locally.  Typically I will create a folder structure in a directory that is backed up to a service like Box.com.  The folder structure can mimic the table structure in ServiceNow, so a folder for sys_script_include, sys_script, sys_ui_script.  Or using friendly names Script Includes, Business Rules and so on.  Don’t get lazy here!  Keeping you files organized will speed things up in the future.

ServiceNow Coding Style Guide Part 1

I thought I would kick of this new blog with a topic that is very important to me,  Coding Style in ServiceNow.  Here I will present a short list of rules and principles to guide your coding.

Following this guide will make your code more readable which will make maintaining the code much easier.  That means less time trying to decipher your or co-workers code and lower costs to maintain code.  This is true of any code base but especially in ServiceNow where the developer ecosystem is so varied.

The end goal is to have all code appear to be written by a single person.

Once a good track record can be established on following these practices then you can start to introduce higher level concepts and principles.  More on those in future articles.

Personally, I disagree with long style guides and best practices documents.  If there are too many rules to start it is impractical for new developers to follow them all.  My approach is to start with the fundamentals.  Once they are mastered then you can layer in more advanced practices.  So for now I am keeping the list short. (It should fit on an index card)

Naming
Functions should be named like verbNoun, using camel case. This will make it easier to remember as well as forcing the function to perform a specific purpose.

Variables should not have abbreviations, ever.  It is preferable to use camel case when creating variables although underscores have started to be used instead.  It does increase readability but most existing code will not follow this.

Classes should always be camel case with the first initial capitalized.

Constants should be all upper case.

All record names should follow a convention.  I prefer Prefix – Script Name, where the prefix is the company name or application name.  This is applicable only where the record name is not the script name such as on Business Rules and Client Scripts.

Script Includes should follow the same convention as classes.  UI Scripts should be all lower case using underscores to separate words.

Formatting
There are two options for brackets, same line or not.  I prefer same line.  As long as you are consistent it is a matter of opinion

Whitespace should be used liberally to increase readability.  I favor using spaces within parentheses.  Line breaks to separate blocks of code within functions and two line breaks between functions.

Edit:  I am going to post this in a new article but I have started not to do this.  Instead I am following the standard of putting spaces outside of the parens.  Which seems just as readable.

Indentation should be 2 or 4 spaces but be consistent.

Semicolons should always be used.

Commenting
By all means, if you feel your code is to complicated use comments to clarify, but before you do that ask, “Can I rewrite this to make it clearer?”  If the answer is yes, rewrite the section and see if the comment is still necessary.  The goal is for the code to document itself.

Odds and Ends
Always use === instead of == to compare values.  This will prevent accidental coercion of variables.

Try and use ‘ instead of ”

Avoid ternary operators

Avoid eval

Principles
Don’t Repeat Yourself.  If you find yourself writing the same code over and over generalize it and move it to a separate function.

Never just copy and paste code.  Always rewrite it and try to understand line by line what it’s doing.  While it’s tempting to just inject a bunch of functionality, that is not going to help if there is an error or you need to modify the code.

Try to keep your code separated by intention.  For instance don’t have a single function that does a database call and then immediately updates the UI.  This is called Separation of Concerns and is the basis for other more specific principles like MVC.  Separated code will make it easier to update and reuse.

Finally, care about your craft.  Your code will likely never hang in a museum but the functionality that you are building matters to your users and it should matter to you as well.

Bonus Cheat Sheet!

Cheat Sheet
Coding Style Guide Part 1 Cheat Sheet