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:
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:
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;
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)
- // Using switch-when statements
- String today = 'Montag';
- switch on today {
- when 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Fritag' {
- System.debug('Go to work');
- }
- when 'Samstag' {
- System.debug('Go to party');
- }
- when else {
- System.debug('Watch movies');
- }
- }
Implemented with switch-when (NOT OK CASE)
- // Using switch-when statements
- Integer currentHour = 12;
- switch on currentHour {
- when 0,1,2,3,4,5,6,7,8,9,10,11{
- System.debug('Gut Morning');
- }
- when 12,13,14,15,16{
- System.debug('Gut Afternoon');
- }
- when else {
- System.debug('Gut Evening');
- }
- }
- BETTER USE IF ELSE
BEB
- // Using if-else statements
- Integer currentHour = 12;
- if(currentHour < 12){
- System.debug('Gut Morning');
- } else if (currentHour >= 12 && currentHour<17){
- System.debug('Gut Afternoon');
- } else{
- System.debug('Gut Evening');
- }
DO
Comments
Post a Comment