0

I was trying to fix a null pointer exception here

if(com.Employee__c != null && (mapEmployees.containskey(com.Employee__c) == null || (mapEmployees.containskey(com.Employee__c) != null && mapEmployees.get(com.Employee__c).Employee_End_Date__c > com.Revenue_Contract_Start_Date__c)))

as mapEmployees.get(com.Employee__c).Employee_End_Date__c

was null here so replaced this block with

if(com.Employee__c != null && (mapEmployees.containskey(com.Employee__c) == null ||
                            (mapEmployees.containskey(com.Employee__c) != null && ((mapEmployees.get(com.Employee__c).Employee_End_Date__c == null) || (
                                mapEmployees.get(com.Employee__c).Employee_End_Date__c!=null && mapEmployees.get(com.Employee__c).Employee_End_Date__c > com.Revenue_Contract_Start_Date__c)))))

But I am still getting the Null Pointer exception at this line (mapEmployees.get(com.Employee__c).Employee_End_Date__c == null)

1

Map.containsKey always returns a true or false value, but never a null value. As such:

mapEmployees.containskey(com.Employee__c) == null 

(true or false) == null

((always false!))

And

mapEmployees.containskey(com.Employee__c) != null

(true or false) != null

((always true!))

And therefore will keep on going through the shortcut AND operator. True or false will never be null, so the first will never pass, and the latter will never fail.

This means that:

mapEmployees.get(com.Employee__c).Employee_End_Date__c

will throw a NullPointerException if mapEmployees.containskey(com.Employee__c) returned false (because the == null will change this to true, and the code keeps going when it shouldn't).

By the way, this really over-the-top logic checking, you usually only care of the value itself was null. The following should suffice:

User employee = mapEmployees.get(com.Employee__c);
if(employee != null && (
    employee.Employee_End_Date__c == null || 
    employee.Revenue_Contract_Start_Date__c == null || 
    employee.Employee_End_Date__c > employee.Revenue_Contract_Start_Date__c)) {

I'm not entirely sure your logic is correct, so this is my best attempt at trying to decipher what you're trying to do, but you can see that simply extracting the map value to a temporary variable has drastically reduced the complexity of your code and makes it easier to understand. This code is also 100% NullPointerException-proof as written.

| improve this answer | |
  • Thanks, @sfdcfox This helped me understand the problem with my code. – Ishan May 27 at 3:49

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.