+ Start a Discussion
ethanoneethanone 

Best way to declare an object variable

Kind of a basic question, but I've seen several ways to set up an object variable and I don't know which is best or if there is any difference.
One Method:
public with sharing class myExtension{
    public Account myAccount{get;set;}
    
    public myExtension(ApexPages.StandardController controller){
        getmyAccount();
    }
    
    public void myAccount(){
        myAccount = [SELECT Id, Name FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }
}
Another Method
public with sharing class myExtension{
    public Account myAccount{
        get{
            if (myAccount != null) return myAccount;
            myAccount = [SELECT Id, Name FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
            return myAccount;
        }
        private set;
    }
    
    public myExtension(ApexPages.StandardController controller){

    }
}

Yet Another:
public with sharing class myExtension{
    public Account myAccount;
    
    public myExtension(ApexPages.StandardController controller){
		myAccount = [SELECT Id, Name FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }
}

And I'm sure there are many other ways and variations out there. But what is the best way? And why is it better (fewer lines, less execution, more reusable, etc)?
Andy BoettcherAndy Boettcher
You're right - all three are completely functional, let me try and give some summary differences between them:

1 - this is if you're using myAccount on a Visualforce page and don't need to do any special logic other than "getting" and "setting" the variable's value.

2 - for use with either just a controller or with a VF page where you want to do some logic behind the get/set each time you reference the variable.

3 - for class-use only (no VF), this is setting a variable just through the constructor for use with other methods in the class.