Server-Side Scripting Best Practices

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

When writing a script that only needs to run in a single context, such as a transform map script, what type of function should you use?

  • Recursive function
  • Anonymous function
  • Global function
  • Self-executing function (correct)

When retrieving a value from a reference field, which method should you use to avoid dot-walking to the sys_id?

  • `getValue("field_name")` (correct)
  • `getParameter()`
  • `getProperty()`
  • `getDisplayValue()`

Why is it recommended to use getDisplayValue() instead of getValue("field name") when retrieving a field's value for display?

  • It is faster and more efficient.
  • It prevents script errors when the field is empty.
  • It automatically formats the value based on the field type.
  • It reduces the need for code changes if the display value changes. (correct)

In client scripts, what is the primary difference between using g_scratchpad and a GlideAjax lookup to get information from the server?

<p><code>g_scratchpad</code> is sent once when a form is loaded, while GlideAjax is dynamically triggered. (C)</p>
Signup and view all the answers

Why should you avoid using current.update() in a Business Rule script?

<p>It can cause a recursive Business Rule that loops indefinitely. (C)</p>
Signup and view all the answers

What is the recommended way to debug server-side scripts in ServiceNow?

<p>Using <code>gs.debug()</code> statements controlled by system properties. (A)</p>
Signup and view all the answers

When should you use Async Business Rules instead of After Business Rules?

<p>When the values that are updating do not need to be shown immediately to the user. (B)</p>
Signup and view all the answers

What is the primary benefit of using Script Includes over Global Business Rules?

<p>Script Includes load only when called, while Global Business Rules load on every page. (A)</p>
Signup and view all the answers

When using setValue() on a reference field in a form, why is it important to include the display value with the sys_id?

<p>To improve performance, as ServiceNow will not need to make an extra call to retrieve the display value. (D)</p>
Signup and view all the answers

In client scripts, what conditional check should be included in onChange client scripts to ensure they run only when necessary?

<p><code>newValue != oldValue</code> (C)</p>
Signup and view all the answers

When working with GlideRecord to count rows, which method should you use to avoid scalability issues as tables grow over time?

<p><code>GlideAggregate</code> (A)</p>
Signup and view all the answers

What should you do before trying out a new script in staging or production instances?

<p>Experiment in a sandbox instance. (C)</p>
Signup and view all the answers

When writing Jelly code, what should you avoid using to prevent performance issues?

<p>Dynamic JEXL expressions inside the Jelly tag (or <code>&lt;g2:evaluate&gt;</code>) (D)</p>
Signup and view all the answers

If you have multiple client scripts on a single table, what should you ensure to control their execution order?

<p>The script order field is set correctly. (A)</p>
Signup and view all the answers

Instead of client scripts, what should you use to set field attributes such as mandatory, visible, and read-only?

<p>UI Policies (C)</p>
Signup and view all the answers

What is the potential impact of using Global Client Scripts?

<p>They load on every page in the system, potentially introducing browser load delay. (D)</p>
Signup and view all the answers

When debugging on the client side, which tools can you use to view logs and identify issues?

<p>JavaScript Log and Field Watcher (D)</p>
Signup and view all the answers

Which type of messages should you search for in the Node Log File Download to diagnose potential system issues?

<p>Slow evaluate, Slow Business Rule, Recursive Business Rule (C)</p>
Signup and view all the answers

What does the ECC Queue primarily control?

<p>The MID Server's communication and movement of data (A)</p>
Signup and view all the answers

Why is it important to review the Event Logs and sort by Processing duration in descending order (Z-A)?

<p>To determine which events are taking the longest time to process, indicating potential inefficiencies. (A)</p>
Signup and view all the answers

Flashcards

Add comments to your code

Add explanatory phrases within the code to clarify its functionality and purpose.

Use Whitespace and empty lines

Employing whitespace and empty lines to delineate logical sections, making code visually easier to parse.

Simplify conditional statements

Favor straightforward if/else statements over complex ternary operators for improved readability.

Modular code components

Divide code into self-contained, manageable units that perform specific tasks.

Signup and view all the flashcards

Construct reusable functions

Creating functions that can be reused across different parts of the application.

Signup and view all the flashcards

Descriptive variable and function names

Choosing names for variables and functions that clearly reflect their purpose and content.

Signup and view all the flashcards

Verify variable value before using

Ensuring that the value of a variable is verified to prevent errors or unexpected behaviours.

Signup and view all the flashcards

Consistent return types

Develop a consistent practice of specifying return types for functions to ensure predictability.

Signup and view all the flashcards

Avoid Eval function

The eval() function evaluates or executes an argument. Improper use of eval() opens up your code for injection attacks.

Signup and view all the flashcards

Use jelly variables

Use jelly.jvar_user_id instead of ${jvar_userid} to avoid issues.

Signup and view all the flashcards

Use addEncodedQuery

Use addEncodedQuery() method to avoid complex gliderecord queries.

Signup and view all the flashcards

Use GlideAggregate for record count

Use GlideAggregate class for simple record counting instead of using getRowCount() method from GlideRecord class.

Signup and view all the flashcards

Add setLimit(1)

Add setLimit(1) to the query method to optimize the query.

Signup and view all the flashcards

Self Executing Functions

Both declared and invoked within the same script field.

Signup and view all the flashcards

Avoid hard coded values

Instead, use system properties and use gs.getProperty and fetch the sys_ids.

Signup and view all the flashcards

Client Script Condition

Client Scripts have no Condition field. This means onLoad() and onChange() scripts run in their entirety every time the appropriate form is loaded. To avoid running time-consuming

Signup and view all the flashcards

System property debug

If the system property debug.MyUtil is set to false, nothing will be output to the log.

Signup and view all the flashcards

Business Rules conditions

Use conditions to avoid the Business Rule running ineficiently

Signup and view all the flashcards

Study Notes

Overview of Server-Side Scripting Best Practices

  • Make code easy to read by including comments and using whitespace and empty lines
  • Use if/else statements instead of ternary operators for better readability
  • Break code into modular components with specialized functions
  • Construct reusable functions for similar logic
  • Use descriptive variable and function names
  • Store function results in a variable to reuse and avoid calling the same function multiple times
  • Verify that the value of a variable exists before using it
  • Return a value when creating functions
  • Avoid using the Eval function due to security risks and debugging challenges
  • Avoid dynamic JEXL expressions inside Jelly tags (<g2:evaluate>) as they can affect memory resources and cause performance issues

Interacting with the Database

  • When using Jelly, use jelly.jvar_user_id instead of ${jvar_userid}
  • Use addEncodedQuery() instead of complex gliderecord queries with multiple addQuery() and addOrCondition()
  • Use GlideAggregate for efficient record counting instead of getRowCount() from GlideRecord
  • Avoid complex queries on large datasets to prevent performance issues
  • Utilize the database for data processing and filtering instead of client or server-side scripting
  • Use self-executing functions for scripts that only need to run in a single context

Avoiding Coding Pitfalls

  • Always test code in a sandbox environment before deploying to staging or production
  • Avoid hard-coding values like sys_ids in scripts; use system properties and gs.getProperty instead
  • Instead of dot-walking to get a reference field's sys_id, use current.getValue("caller_id")
  • Use getDisplayValue() instead of getValue("field name") to avoid code changes if the display value changes

Client-Side Scripting Best Practices

  • Use client scripts to validate data
  • Ensure the correct script order for multiple client scripts on a table, where lower order values execute first
  • Use UI policies to set field attributes like mandatory, visible, and read-only instead of client scripts
  • Restrict list editing to avoid conflicts between client scripts/UI policies and list editing
  • Only run necessary client scripts to avoid performance issues
  • Use newValue != oldValue in onChange client scripts
  • Ensure isLoading and newValue checks exist in onChange Client scripts
  • Call GlideAjax only when necessary, checking values beforehand to avoid unnecessary server lookups
  • Enclose code in functions to prevent variable collisions

Minimizing Server Lookups

  • Use client-side data whenever possible to reduce server lookups
  • Use g_scratchpad and asynchronous GlideAjax lookups to get information from the server
    • g_scratchpad is sent once when a form is loaded, while GlideAjax is triggered dynamically
  • Avoid GlideRecord and g_form.getReference() callbacks due to performance impact
  • When using setValue() on a reference field, include the display value to avoid synchronous Ajax calls

Client Scripting Practices to Avoid

  • Avoid Global Client Scripts, as they load on every page and cause browser load delays
  • Avoid DOM Manipulation, except in UI Pages and the Service Portal, and use GlideForm API instead

Business Rules Best Practices

  • Ensure the when field is carefully considered when writing Business Rules
  • Use Async Business Rules instead of after Business Rules if the updated values do not need to be immediately shown
  • Use Conditions in Business Rules to avoid unnecessary evaluations
  • Enclose code in functions to avoid variable conflicts
  • Prevent Recursive Business Rules by avoiding current.update() in a Business Rule script
  • Use Business Rules to double-check critical inputs
  • Use Script Includes instead of Global Business Rules, as Script Includes load only when called

Debugging Best Practices

  • For server-side debugging, use the debug navigation filter
  • Use System Diagnostics > Debug Log to display gs.debug(), gs.info(), gs.print(), and gs.log() statements
    • gs.print() and gs.log() are unavailable in scoped applications
  • System Diagnostics > Debug Business Rule displays messages about business rules
  • System Security > Debug Security Rules places a debug icon on each field to display debug messages
  • Use gs.debug() statements controlled by system properties for server-side debugging
  • For client-side debugging, enable JavaScript Log and Field Watcher
  • Use jslog() statements in client scripts and UI policy scripts
  • Check the browser's console log for additional debugging information
  • Disable server-side debugging before closing an update set or completing testing

Logs and Queues

  • Review warnings and errors in logs and queues frequently
    • System Logs > System Log > All shows all warnings and errors
  • Regularly check the size of log files via System Logs > Node Log File Download.
  • Review recent log files (files with names that start with localhost_log) and search for messages that may indicate potential issues:
    • Slow evaluate
    • Slow Business Rule
    • Recursive Business Rule
    • Compiler exception
    • Warning - large table limit
    • Extremely large result
  • Diagnose performance issues by reviewing the Slow SQL Statements log
  • Check the ECC Queue to identify any problems with the instance or MID Server
  • Reviewing Event Logs records all system events that occur within ServiceNow
  • Improve overall system performance by removing unused events

Update Set and XML Data Transfer

  • Use a well-defined migration process for moving changes between instances
  • Create an ordered list detailing how grouped update sets should be applied
  • The migration procedure should include information about any additional data or configuration changes required to accompany the update sets
  • Need instructions for:
    • Activating plugins
    • Configuring system properties or other instance-specific settings
    • Setting up MID Servers and identity servers
    • Ensuring that the target table is available
  • Export XML data from one instance and import it to another to migrate data
  • Migrating data in an XML file saves time for unscheduled data imports since there is no need to build an import set or a transform map
  • Adding a comment in the update set description is good practice so the user installing the update set is aware that an XML import is required
  • Importing XML preserves data without firing business rules or updating the instance cache
  • Only the selected record will be exported, not the records related to it

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Server-side Scripting cu PHP
8 questions
Server-Side Scripting with PHP Overview
40 questions
Server-side vs Client-side Scripting
37 questions
Server-Side Web Scripting Overview
16 questions
Use Quizgecko on...
Browser
Browser