-2

I am in curious of knowing which way is the best to check any empty values in apex. For eg, in apex email service I need to check whether the subject is empty or not.

Way 1:

String subject = email.Subject;
if(!String.isBlank(subject)) {
//Do something
}

Way 2:

String subject = '';
if(!String.isBlank(email.Subject)) {
subject = email.Subject;
//Do something
}
4
  • In both ways, you are checking empty in same fashion....what is difference? – Ayub Feb 27 '19 at 10:00
  • In Way 1, I'm not checking whether the incoming value is empty or not.I'm directly assigning email subject to a String and then checking if that string is empty. But in the Way 2 I'm checking if the incoming value is not empty then assign to a variable. – uma451 Feb 27 '19 at 10:14
  • I think that best way to check if the string is NOT blank is by using isNotBlank() method rather than !isBlank() – Novarg Feb 27 '19 at 13:24
  • Can you explain what significant difference is there between these two – uma451 Feb 28 '19 at 11:36
1

String.isBlank() Returns true if the specified String is white space, empty (''), or null; otherwise, returns false. So, for both ways, this String.isBlank is gonna work in same way.

Only difference in both statements is, in first method, subject variable may assign to null value; and if you are using it without checking null value in further, you may get exception but in second one you will not get that.

String subject = email.Subject; //assume email.subject is null
if(!String.isBlank(subject)) {
//Do something
}
//do something after if block like
string lowercaseSubject = subject.oLowerCase(); // it will throw null pointer exception error because subject is null...

So either follow the second approach or use first one with null pointer check as below:

string lowercaseSubject = subject!=null?subject.oLowerCase():'';

I hope now it's clear.

P.S: You can use String.isNotBlank(inputString) as well.

1
  • So out of both Way 2 is better as you said. Thanks for the clear explanation Ayub – uma451 Feb 27 '19 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.