An as example, say I have a trigger (list object) with accounts in it, and I want to compare the "Status" attribute of an account to a String. This is how I do it right now:
if (trigger.oldMap.get(account.id).Status__c != null && trigger.oldMap.get(account.id).Status__c.contains('active')) {}
My true purpose is simply to execute the second expression, but in the case that the current account did not have a Status, I would be returned a NPE because of the compareTo call. So I add in a not null check first which seems like a terribly inefficient way of doing things.
How can this be done better?
Trigger.oldMap.get(account.Id)
in a variable.if (trigger.oldMap.get(account.id).Status__c == null ? false : trigger.oldMap.get(account.id).Status__c.contains('active')) {}
Its actually slightly longer in this case, but I think can be cleaner for more complex evaluations. Agree with @phil-r - you are more likely to be using a variable, in which case you might have:if (oldItem.Status__c == null ? false : oldItem.Status__c.contains('active')) {}