2

When should you use Apex Properties vs. nornmal setters and getters?

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_properties.htm

4

The Apex Properties method is typically used as part of a Visualforce controller when you have an action method that calls a method within a controller where you also expect to return or "set" a value. Below is a "lazy" load example where rather than explicitly setting the value, it returns it when called and only when the existing value is null.

public Account getMyAccount() {
   if (MyAccount == null) {
      MyAccount = [SELECT name, annualRevenue FROM Account
      WHERE
      id = :ApexPages.currentPage().getParameters().
      get(‘id’)];
   }
   return MyAccount;
}

Note that this type of code is used to implicitly set all of the field values related to the Account that are returned in the query. It could have been coded to specifically set each field as well. The above is more efficient, allowing the page to use what it needs.

Edit:

Lazy loading is described in the pdf Visualforce in Practice. How a page loads and the order in which things are evaluated can be rather complex in a Visualforce page depending on the custom controller, the page's design and any user actions taken. This is discussed in the Visualforce Developer’s Guide in the section titled Order of Execution in a Visualforce Page where you'll find examples that illustrate the concepts involved.

2
  • is there an order of evaluation thing between nornal setters and getters and properties? or do they do lazy loading too? Sep 5 '15 at 17:50
  • See my edits to respond to your question. Lazy loading is something that happens through design. Its not something that happens when variables are declared public with {get,set} outside of a getter/setter method that's nested within an outer class.
    – crmprogdev
    Sep 5 '15 at 19:04

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.