You need to sign in to do that
Don't have an account?

Best Practices: Constructor or Initialization?
Been reading the docs (Using Constructors & Using Initialization Code) trying to understand when to use initializer vs. constructor. In the "Using Initialization Code" link it is stated:
If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor to do initialization and not use instance initialization code.
It's a bit vague. Is there a good rule of thumb to follow?
Cheers,
Tyler
if you're in visualforce, and are using any of the ajax tags a lot (actionfunction, actionsupport, etc), you would be wise to bind any "sticky" UI list elements to variables that are set in a constructor, rather than having properties or getter methods that directly query the DB to get the data. this is because whenever you call the "action" of one of these ajax methods, all getters are called, which causes your ajax stuff to appear slower than it normally would.
Example (unoptimized)
the above example, once extended with other public methods/properties, would call getAccounts for every ajax action you put into the page, regardless of whether you wanted to refresh that accounts list or not. Since this scenario would be more useful if getAccounts() were only querying once (for instance, on render/page load), we move it out of a getter method, and instead populate a variable via the constructor.
in this version, the accounts list is populate via the constructor, so other page interactions will not trigger additional SOQL queries, which, as you build richer pages, can severely bog down the performance when using actionfunction/actionsupport/ajax in Visualforce.
Rule of thumb, if it's something that's populated on page load, and doesn't need to change via ajax, do it in the constructor, not a getter/property.
Doing the above via initialization code achieves the same effect in my experience, but I prefer creating the custom constructor definition vs. standalone initialization blocks. With the constructor, you also have complete control over the order of operations as the page is rendered.
that is some good advice on the Ajax. Thanks!
One thing I've been playing around with is using initialization statements after each variable declaration in the header of my class. What I like about this so far is that it is very easy to understand at first glance to what value the variables are being initialized. As opposed to seeing the variables declared in the header and then cross-referencing to the constructor.