function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tan JTan J 

Best optimized way to get logged in user info and set variables in apex controller

I want to know the best optimized way to access current logged in user's information and set few flags. I have a controller extension and I have set flags in constructor like this:

 User u = [SELECT ID,Name,ProfileID,Profile.Name,UserRole.Name,UserRole.ID,Team_Lead__c,Leading_Teams__c,Department,Desk__c
             FROM User 
             WHERE id=:userId];

if(u.UserRole.Name != null && u.UserRole.Name.contains('xyz')){
                isComUser = true;
      }      
            if(u.UserRole.Name != null && u.UserRole.Name.contains('pqr'))   { 
                isFPUser = true; 
}


...and the conditions go on..
There are so many conditions that constructor has become really big & unmanagable.

Is there a good way to do this? Thanks in advance
logontokartiklogontokartik
Well. you can just user the User instance to check for validations, I am not sure where you are using the flags but you can directly use the user Instance to check for conditions and this will eliminate the need to define booleans.

If its your Visualforce page, you can directly use either user instance or global VF variable !$User.

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_variables_global_user.htm
Tan JTan J
There are some boolean flags, some string etc. which are set based on conditions like user, profile, role etc. Sometimes there is a complex logic too. The flags are used in other apex methods in that class and VF page. There are many sections on the VF page which render based on these flags. Also, there is a page redirection which happens based on who logged-in user is. The action is called on the page load. In short, I want to know the best ideas to optimize this and also reduce the number of lines of code. (I am already thinking of using cutom settings in place of hard coded profile names currently i have). I have also seen posts where people are using separate class for accessing user info and calling it from this controller.
Tan JTan J
Any ideas on this please?
Tan JTan J

Any ideas on this would be appreciated.