Operator Part 1

 In Salesforce, the Safe Navigation Operator (?.) is a feature introduced in Winter '21 that allows for safe access to fields or methods in an object, preventing null pointer exceptions. If the value before the ?. operator is null, it will return null instead of throwing an error.

Here’s how it works:

Syntax:



Object?.Field

Example:

Consider you have an Account record and you want to access a related Contact's first name. If the Contact field is null, it would normally throw an error when trying to access the first name. With the Safe Navigation Operator, you can safely access it like this:


String firstName = account?.Contact?.FirstName;

If account or account.Contact is null, it will safely return null without any exceptions being thrown.

Benefits:

  • Prevents null pointer exceptions.
  • Reduces the need for nested null checks.
  • Makes code more readable.

This is particularly useful in scenarios where you are not sure if an object or its related objects might be null, and you want to handle that safely.



-------------


Null Coalescing Operator

Integer notNullReturnValue = anInteger ?? 100;


string name = null; string displayName = name ?? "Default Name";

In this example, since name is null, displayName will be assigned the value "Default Name".


--------


Switch is preferred when comparing with exact values


Implemented with switch-when (OK CASE)

Comments

Popular posts from this blog

API Names in Salesforce

18 - LWC - BEST PRACTICES - For accessing HTML elements and their values in JavaScript

6 - Object Relationships (Lookup and Master-Detail and Junction Objects)