1

When writing a future method, I wrote 3 static properties for this future method.

Here's an example:

global class MyTestClass {
private static Date month1start
{
    get 
    {           
      if (month1start == null){
          integer currentmonth = System.today().Month();
          integer currentyear = System.today().year();
          integer month1=currentmonth;//first month of current quarter        
        if(math.mod(currentmonth,4)==2){
            month1=month1-1;
        }else if(math.mod(currentmonth,4)==3){
            month1=month1-2;
        }
          Date month1start = date.newinstance(currentyear, month1, 1);              
      }            
      return month1start;
    }
    private set;
}
private static Date month2start
{
    get 
    {           
      if (month2start == null){
             month2start = System.today();
               month2start=    month1start.AddMonths(1);   
      }                     
      return month2start;
    }
    private set;
}
private static Date month3start
{
    get 
    {           
      if (month3start == null){
        month3start = System.today();
               month3start=    month2start.AddMonths(1);

          }                     
      return month3start;
    }
    private set;
}

public static void staticmethod(){
    System.debug('month3start: '+month3start);
}
}

When I execute anonymous code:

MyTestClass.staticmethod();

I got error message "System.NullPointerException: Attempt to de-reference a null object"

I thought when accessing "month3start", "month2start" and "month3start" would be created.

Sorry I'm not able to understand this by reading materials online.

2

Its a silly mistake!

You are creating a new variable here and assigning value to it but the actual month1start is still null and returning the null one.

Date month1start = date.newinstance(currentyear, month1, 1);  

Change the above line to

month1start = date.newinstance(currentyear, month1, 1); 

and you will be fine!

  • Your answer might be more useful if you explain and/or link to how properties work. – Adrian Larson Apr 13 '16 at 13:35
  • You're right! I should update the answer – Santanu Halder Apr 15 '16 at 7:37

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.