All Ideas

Idea Details

Post an Idea
1,280  Points
Open
Idea has been posted. Give it an upvote or downvote.

Null Coalesce Operator

Apex & Visualforce

One of the most common operations we're faced with every day is considering if a value is null or not before we use it. Currently, we're forced to write the same verbose code over and over again, either by branching or ternary operators.
String[] parts = (source==null? '': source).split(',');
Or, alternatively:
String[] parts;
if(source == null) {
    parts = new String[0];
} else {
    parts = source.split(',');
}
This type of pattern appears in almost any non-trivial class or trigger, and probably appears hundreds of times in a typical project. We use them for default values, and to provide a non-null reference for many of the operations we have in salesforce, since most of the standard library will throw exceptions with null parameters.

It seems like virtually other modern language has a concept of null coalesce operators.
... JavaScript, Ruby, etc
x = y || 10;

... C#, PHP 7, Swift, etc
x = y ?? 10;

... Perl, etc
x = y // 10;

... ColdFusion (with parenthesis), PHP 5.3+
x = x ?: 10;
Java is, of course, notably missing from the list, but that doesn't mean that we shouldn't have such a useful language feature. Ternary operators require specifying the left-hand variable twice to get a result if it's not null, if statements are bulky and cost more time to get code coverage for, and utility methods require more CPU time (by approximately double).
 

Merge Idea · Flag

  • Upvotes
  • Downvotes

Ideas

Apps

from AppExchange

Questions

Help us to keep IdeaExchange clean by pointing out overlapping ideas. We'll investigate your suggestion and merge the ideas if it makes sense.



 

 

Thanks for your merge suggestion. We will review it shortly and merge the ideas if applicable.

Salesforce takes abuse situations very seriously. Examples of abuse include but are not limited to posting of offensive language or fraudulent statements. To help us process your request as quickly as possible, please fill out the form below describing the situation. For privacy and security reasons, the final outcome of an abuse case may not be revealed to the person who reported it.


 

Thank you for your feedback. We take abuse seriously and will investigate this issue and take appropriate action.