Monday, December 13, 2021

Javascript: Working with Arrays using Asynchronous operations

Let’s say we have a list of names. For each name, we want to make an API call and get some information, and then keep a new list with this collection of information. A typical approach may look like this.

Refactoring to using map or forEach is not that straightforward here. The callbacks provided to map or forEach (or any of the array-methods) are not awaited, so we have no way of knowing when the full collection of information is done and ready to use. However, there is still a way we can write this in a nice way. Using the Promise.all method.

Awesome! Now, map returns a list of promises, and the Promise.all method takes a list of promises and resolves them in parallel. Not only did the code become much more nice and clean - but we also benefit from the fact that the promises are not resolved sequentially, which speeds up the process and increases performance.

Share This:    Facebook Twitter

Javascript: sort() and Array destructuring

Take a look at the code below.

At first glance, this looks good. We’re not using let, and we’re not mutating on the original array using something like push. But take a look at the console.log statement. It turns out that the sort method does not create a copy of the original array. Instead, it both mutates on the original array and returns its own array from the method call.

And there are a handful of old Array-methods that do this. Be careful with push, shift, unshift, pop, reverse, splice, sort, and fill. Fortunately, most often we can simply avoid calling these methods at all, to stay out of trouble.

However, there are cases, like using sort, where we have to use a method that mutates the original array, in lack of better options. Array destructuring to the rescue! Whenever these occasions arise, make sure to manually copy the array first, before performing an operation on it. It’s as simple as this.

That [...grades] makes the entire difference.

Share This:    Facebook Twitter

Javascript: Pass arguments as an object

Say we have a function, createUser, which requires four arguments in order to create a new user (by calling some API).

When looking at the function signature itself, things seem to make pretty good sense. But how about when we call it?

It’s pretty unclear what the arguments mean, right? Especially the last two booleans. I would have to go to the implementation to look it up. Instead, we can wrap the arguments in an object.

Thanks to ES6 object destructuring, we can do this easily by simply adding curly brackets around the arguments. Now, whenever we call createUser, we pass an object as a single argument with the required values as properties instead.

See how nice that reads out now. We’re no longer in doubt what those booleans mean. There’s another version of this that I’ve seen very often: Passing optional arguments as an options object. The idea is to pass 1-2 essential arguments and then pass the remaining arguments as an options object.

Now we need to check if the options object is set before accessing its values and provide proper fallbacks. On the other hand, calling the createUser function now looks very clean.

The first two arguments are pretty obvious, and we can now optionally provide options when needed.

Share This:    Facebook Twitter

Javascript: Guard clauses and avoiding using 'else'

Guard clauses

“In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. Regardless of which programming language is used, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution.”

— Wikipedia

Let’s take a look at an example. We have a function, getValidCandidate, which checks if a candidate is valid, provided a list of members and returns the member if the candidate is valid, or undefined otherwise.

Look how nested the code is? Ifs wrapping other ifs, nested 3 times. Let’s rewrite this and use guard clauses instead.

Guard clauses prevent the function from continuing what it’s doing and instead returning early if the guarding condition is not met. Naturally, we also know that the end result is the last return of the function.

Skip the ‘else’ part

Whenever you’re about to write else, stop and reconsider what you’re doing and search for an alternative way to express the logic.

Let’s cover a few ways that we can avoid using else. One of them is guard clauses, which we just covered above. Another approach is using default values. Let’s take an example.

Let’s say we have a function, negateOdd, which takes a number and negates it if the number is odd.

The function does what it’s supposed to. But it’s unnecessarily using an else. Let’s refactor it, and instead, use a default value.

We now assign result with a default value, and the variable will only be changed if the condition in the if-statement is met. But let’s do even better. We’re supposed to question the use of let and imperative (altering the state of your program step by step) code. Let’s see if we can make this function even more readable and concise.

There is a version of if-else that is generally accepted. It’s the ternary operator.

Share This:    Facebook Twitter

Sunday, December 12, 2021

NodeJS & AWS Lambda

NodeJS is a backend runtime environment that runs on the V8 engine and enables us to write and execute server-side JavaScript.

Use promises instead of callbacks

NodeJS was originally built using a callback pattern for asynchronous calls. All of NodeJS’s builtins are structured this way: you provide the main arguments along with a callback function that is applied when the asynchronous operation is done.

Fortunately, it’s quite easy to convert these methods to using promises instead. Let’s look at two different ways.

Using promisify

You can use a utility function, promisify, from the utils module to wrap the function using a callback in a promise.

It works for all functions that follow the NodeJS callback convention, which means that it works for a range of old third-party libraries for NodeJS as well.

Using module/promises

Instead of handling the promise-wrapping yourself, all NodeJS builtins come with a promisified version of their functions, straight from the module itself. This is, by far, the easiest way to use promises in NodeJS. Please, stick to this pattern anywhere you can.

Async handlers in AWS Lambda

The same goes for AWS Lambda. You don’t have to use the callback argument anymore. Instead, declare the handler as async, and return the result instead.

If you need to fulfill promises during the function call, you simply apply the await keyword like you normally would.

Share This:    Facebook Twitter

Tuesday, February 23, 2021

Salesforce Lightning: Assign a record to yourself

Let's assume that you want to assign an account or multiple account records to yourself from the detail record view and the list view respectively. You can easily implement the same using only flows if you want to take up a declarative approach.

I have created an autolaunched flow which accepts both single and multiple record ids. Care should be taken that the name of the variables should be exactly id and ids respectively.

To call this flow, create a custom button each for detail and list page and add it on the layout pages. So for the detail page, set the id flow variable to be the account ID, and once the flow is completed, redirect the user to the same account detail page by providing the retURL parameter in the flow URL.

For the list view page, make sure that Display Checkboxes is selected. The ids variable is populated automatically when one or more records are selected in the list view page. The only caveat is that once the flow is completed, I couldn't find a declarative way to redirect the user to the same list view page from where the flow was executed (you can use a Visualforce page to redirect to the list view). So for the sake of simplicity, I am redirecting the user to the Recently Viewed Accounts page.

Next, we have to add these buttons. To add the button on the detail page layout,

and to add on the list view page,

You can get the flow and the associated custom buttons files from this repository.

Share This:    Facebook Twitter

Thursday, January 28, 2021

Salesforce Classic: Assign a record to yourself

Let's consider a use case where you want to assign a record (in this case, Workorder) to yourself. To implement this scenario, click on New Button or Link button. Enter the details as below:

and provide the below script:

{!REQUIRESCRIPT("/soap/ajax/49.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/49.0/apex.js")}

var __sfdcSessionId = '{!GETSESSIONID()}';
sforce.connection.sessionId = __sfdcSessionId;

var workOrder = new sforce.SObject("WorkOrder");
workOrder.Id = "{!WorkOrder.Id}";
workOrder.OwnerId = sforce.connection.getUserInfo().userId;
result = sforce.connection.update([workOrder]);
 
if (result[0].getBoolean("success")) {
    console.log(result[0].id + " updated");
} else {
    console.log("failed to update " + result[0]);
}
window.location.reload();

Now add this button on the page layout.

Share This:    Facebook Twitter

Sunday, January 3, 2021

Improving Salesforce Apex Performance

Improving CPU Time

In general, there are two ways to improve the CPU usage:

  • Work on a smaller amount of data (that is, do less work).
  • Operate on the data in a more efficient manner.
Faster for loops

In the following code snippet, we are using the SOQL for loop format to loop through the account records and a traditional iterator-style for loop:

List<Account> accs = AccountSelector.getAccounts();

Integer max = accs.size();
for (Integer i = 0; i < max; i++) {
   System.debug(accs[i].Name);
}
for (Account acc : AccountSelector.getAccounts()) {
   System.debug(acc.Name);
}

As per the tests, the iterator loop runs faster than the SOQL for loop. Therefore, we should use the iterator format for best performance in CPU time, though we do use a lot more heap size in the iterator.

This is an important example that highlights the fact that when optimizing for one governor limit, we will often impact another.

Using maps to remove and reduce looping

The simplest use case is when retrieving a list of records from a query and then putting them into a map so that you can retrieve a record using its ID.

Map<Id, Account> accsById = new Map<Id, Account>([SELECT Id, Name FROM Account]);
Account myAccount = accsById.get(myAccountId);
Reducing the use of expensive operations

If we wanted to retrieve the Name field of our account record and assign its value to a variable, we could do it in one of two ways. We could either call the Name field using a static reference or call the get method on the record, passing in the field name.

String accName = acc.Name;
String accountName = (String)acc.get('Name');

The second option is slower and more CPU intensive than the first one.

Another commonly used dynamic call is to the Schema class to retrieve information about metadata within the org. The simplest way to handle these situations is to cache values locally in variables for reuse. If you are making repeated calls to any of that describe information, you should work to cache these results in a local variable outside the loop, which will remove the need to make repeated calls and reduce your CPU time overall.

Reducing Heap Size Usage

The heap size is the amount of memory being used to store the various objects, variables, and state of the Apex transaction in memory as it is being processed. For synchronous operations, this is capped at 6 MB and is doubled to 12 MB for asynchronous processes.

Using scoping

We can either declare variables at a class level or within a code block (a method, loop, and so on) within Apex. Declaring a class-level variable means that the variable will be available in memory for the lifetime of the instance of that class, while variables declared in a code block will only be available for the scope of that block.

Structuring your code well into discrete functions with limited scope will help to ensure that your code avoids the heap size limit by allowing the Apex memory manager to handle memory effectively.

Removing unwanted items

Let’s refer the code snippet for the traditional iterator-style for loop we had used earlier. A simple action of setting the value of the accs variable to null reduces the heap size we are consuming.

List<Account> accs = AccountSelector.getAccounts();

Integer max = accs.size();
for (Integer i = 0; i < max; i++) {
   System.debug(accs[i].Name);
}
accs = null;

It can be useful therefore to remove any unwanted items from memory manually if you are working with large sets of data or the Blob data type and wish to free space to ensure that you do not hit the heap size limit. Combining this with scoping will help you ensure that the memory of your applications is well managed and, in most instances, you will have no concerns with the heap size limit.

Improving Query Selectivity

In order to achieve the best performance possible, we want to make our query as selective as possible to reduce the number of records returned.

The first thing that indicates selectivity is whether the field is indexed. The following types of field are indexed:

  • Standard primary keys (Id, Name, OwnerId)
  • Foreign key fields (CreatedById, LastModifiedById, lookup relationships, master-detail relationships)
  • Audit fields (CreatedDate, SystemModstamp)
  • Custom fields marked as unique or External Id

If a field is indexed, it will be considered for optimization. Following this, the optimizer then determines how many records are returned using that index. The following calculation is made to determine whether the number of records selected is below the following thresholds:

  • For standard indexes, 30 percent of the first million targeted records and 15 percent of the remaining records. The threshold is 1 million records.
  • For custom indexes, 10 percent of the first million targeted records and 5 percent of the remaining records. The threshold is 333,333 records.

If the indexed field meets these thresholds, it is considered selective and will be considered for optimization. Salesforce provides developers with the Query Plan tool in the Developer Console that will provide detailed information on whether a query is selective or not. To enable this in the Developer Console, open the Preferences menu and select the Enable Query Plan option. Once you have selected this option and saved, using the Query Editor pane, you can enter a query and use the Query Plan button to view metrics on the selectivity of a query. The statistics returned here inform us of which filter would be used (if any) and why. The columns presented have the following information:

  • Cardinality: The number of records returned by this operation.
  • Fields: The indexed fields used by the optimizer in this operation. This will be null if the field is not indexed.
  • Leading Operation Type: The primary operation used by the optimizer to optimize the query, one of either Index for an indexed field, Sharing for sharing rule-based control, TableScan if a full search of the object occurs, and Other if an internal Salesforce optimization is used.
  • Cost: This is a cost score for running the query. Any value over 1 is considered non-selective. We should always aim to have a query with a cost of 1 or less.
  • sObject Cardinality: The approximate, number of records on the object.
  • sObject Type: The object we are querying.

The other key practice when defining WHERE filters is to attempt to use positive/ inclusion operations (IN, =) rather than negative/exclusion operators (NOT, !=) as these exclusion operations are not optimizable, except when using != null and != boolean. It is a good practice therefore to ensure wherever possible that you use positive/inclusion operations to improve optimization chances.

Number of Queries

There are also a couple of simple ways in which you can reduce the number of queries you are running.

Retrieving child records with a sub query

If retrieving a record and you require child records, consider using a sub query where appropriate to help retrieve all the necessary data at once. This is not always necessarily a good practice; for example, when determining the Batch Apex scope, it is more performant to select the parent records in the batch scope and retrieve the child records in each batch. If you are working with a selective query on the parent record and retrieving a small set of data for each returned record, then this can help avoid additional loops, mapping, and queries.

Cache results

If the data is not expected to change during the transaction, a developer can use the singleton pattern to cache results that were retrieved. This is an extremely effective tool when retrieving setup-related objects (Profile, Holiday, Role) or custom metadata or custom settings. None of these items should change during the course of a transaction and are slow-moving data, making them comfortably cacheable for the duration of the transaction.

Platform Cache

Platform Cache is a powerful feature that can enhance the performance of applications when working at scale and requiring data to be retrieved in a regular fashion, but that does not change regularly. A free allocation of 10 MB of cache is provided for Enterprise Edition orgs, and 30 MB for Unlimited and Performance Edition, with a greater allowance available for purchase. If you are working in an environment where there is a set of data that is retrieved regularly but does not change, and you have available a Platform Cache allocation, then consider it as a possible enhancement to help improve your system's performance.

Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top