+ Start a Discussion
ElmilandElmiland 

Null != Field vs. Field != Null

Before updating a field ABC, I need to check whether the field is passed as null/blank, if yes, then dont update it.

Can someone advise if there is a difference between the two options below, and if yes, what I should be aware of? I am interested if wither there is a best practice, potential compile errors, or anything else.

Option 1:
if ( null != ABC && '' != ABC ) {
               abc.ABC__c = ABC;               
            }

Option 2:
if ( ABC != null && ABC != '' ) {
               abc.ABC__c = ABC;               
            }

Thank you!
Hargobind_SinghHargobind_Singh
I don't think there should be any difference. However, from maintenance perspective, someone could have a hard time if fields are written on right and values on left. 

Salesforce documentation says: 
 
Inequality operator. If the value of x does not equal the value of y, the expression evaluates to true. Otherwise, the expression evaluates to false.
Note:
String comparison using != is case-insensitive
Unlike Java, != in Apex compares object value equality, not reference equality, except for user-defined types.
For sObjects and sObject arrays, != performs a deep check of all sObject field values before returning its result.
For records, != evaluates to true if the records have different values for any field.
User-defined types are compared by reference, which means that two objects are different only if they reference different locations in memory. You can override this default comparison behavior by providing equals and hashCode methods in your class to compare object values instead.
x or ycan be the literal null.
The comparison of any two values can never result in null.


 
BalajiRanganathanBalajiRanganathan
I would use String.isBlank() function.

if (!String.isBlank(ABC)) {
}
BalajiRanganathanBalajiRanganathan
also we have isNotBlank function


 
ElmilandElmiland
thanks all!