+ Start a Discussion

Flow of the APEX code


I just want to know the flow of the control for this below code.

UserCacheLoaded = False , then when we are using this variable in the IF, it will not go Inside the code. And henceforth, CacheUserInfo() method will never be called. 
Can someone explain this? Thanks in advance...

public class ThinkingInApex{

 private static Boolean UserCacheLoaded =  false;
 private static Boolean UserIsSpecial =  false;
  private static String UserTimeZone =  false;
  public static Boolean IsUserSpecial(){

      return UserIsSpecial;
      return UserIsSpecial;

private static void CacheUserInfo(){
  if(UserCacheLoaded) return;
User u = [SELECT UserIsSpecial__c, TimeZoneSidKey FROM User where ID =: UserInfo.getUserId()];
 UserIsSpecial  = u.UserIsSpecial__c;
 UserTimeZone  = u.TimeZoneSidKey;
 UserCacheLoaded = True;

Best Answer chosen by Kaity
In general programming language, if there is no set bracket({ }) is mentioned for IF condition, then it will consider only next one line for the scope if condition. 

If you are calling the method like this ThinkingInApex.IsUserSpecial();

1. It will check for the If condition UserCacheLoaded, the varibale is false it won't enter into next time, then it will execute 3rd line the CacheUserInfo() method
2. Then in the CacheUserInfo() it will check for the if condition, again the variable is false, then it will execute query to hold the all the value and in the final line it will set the UserCacheLoaded = True
3. The execution will go the IsUserSpecial() method and return the UserIsSpecial value.

If the same code is called once again in the same execution it won't run the SOQL query each time to check to get the UserIsSpecial value. This sample is code to understand the use of the Static varaible in apex language.