function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kryan0618kryan0618 

Best practice for concatenating values in APEX

I am currently writing APEX code to evaluate web-to-lead information and build a multi-select field on the Lead object based upon the user entries. I would like to know the best practice on how to handle.

I'm a little unsure how to handle concatenation of the values.

Example of a portion of the code:

if(newLeadMap.get(newLeads.get(leadB.email)).Beauty_Blog__c == True) {
leadB.Subscriptions__c = leadB.Subscriptions__c + 'Beauty;';
}
if(newLeadMap.get(newLeads.get(leadB.email)).Entertainment_Blog__c == True) {
leadB.Subscriptions__c = leadB.Subscriptions__c + 'Entertainment;';
}

This works fine if leadB.Subscriptions__c already has a value. However, you cannot concatenate to a null value.

So, my question is... how do I handle if it is null? Do I have to perform a check each time I want to perform the concatenation? Or am I going about this wrong and should be using a different method to build my field?

Thanks in advance!

Best Answer chosen by Admin (Salesforce Developers) 
Avidev9Avidev9

Well the answer is yes you have do a null check before doing a concat else you will get a value like "My Valuenull"

Well there wont be much change. You can use ternary operator to replace null with blanks

 

String Subscriptions = leadB.Subscriptions__c == NULL ? '' : leadB.Subscriptions__c;
if (newLeadMap.get(newLeads.get(leadB.email)).Beauty_Blog__c == True) {
    leadB.Subscriptions__c = Subscriptions + 'Beauty;';
}
if (newLeadMap.get(newLeads.get(leadB.email)).Entertainment_Blog__c == True) {
    leadB.Subscriptions__c = Subscriptions + 'Entertainment;';
}

 

All Answers

Avidev9Avidev9

Well the answer is yes you have do a null check before doing a concat else you will get a value like "My Valuenull"

Well there wont be much change. You can use ternary operator to replace null with blanks

 

String Subscriptions = leadB.Subscriptions__c == NULL ? '' : leadB.Subscriptions__c;
if (newLeadMap.get(newLeads.get(leadB.email)).Beauty_Blog__c == True) {
    leadB.Subscriptions__c = Subscriptions + 'Beauty;';
}
if (newLeadMap.get(newLeads.get(leadB.email)).Entertainment_Blog__c == True) {
    leadB.Subscriptions__c = Subscriptions + 'Entertainment;';
}

 

This was selected as the best answer
kryan0618kryan0618

Awesome! Thank you. That is EXACTLY what I needed to know!!

Avidev9Avidev9
Was it resolved ?
If yes can you mark the answer as solution so that others can also refer this.
kryan0618kryan0618

I am testing the theory out right now.