4

There are already many threads on the confusion with Visualforce's Lifecycle/Execution Order, as their should be because its pretty confusing the more complicated your applications becomes. With that said, I assure you I've read many threads, articles, and SF documentation to prior to this post but I still have a question.

Understanding that a controller/extension's constructor executes before the getters, I had a situation where that didn't seem to be the case but I believe it is because of a misunderstanding about syntax.

If I setup a get;set; like this:

public List<Object__c> dropdown_list { get; set; } {
    // I thought this was setting up the getter 
    // but if I add a debug here it fires BEFORE
    // the constructor
}

But if I swap the syntax to the following:

public List<Object__c> dropdown_list { 
    get{
        // Now the execution order fires as expectedhow 
        // AFTER the constructor
    } set; 
}

Why is this? What am I not understanding about this and what is the proper terminology for the two structures (as well as any other unlisted scenarios)?

1 Answer 1

9

What is happening is that you are actually using an Initialization Block. See Static and Instance Methods, Variables, and Initialization Code (Using Initialization Code).

Using Initialization Code

Instance initialization code is a block of code in the following form that is defined in a class.

{
    //code body
}

The instance initialization code in a class is executed each time an object is instantiated from that class. These code blocks run before the constructor.

This block has nothing to do with your getter or setter, but is completely separate.


If you use more conventional whitespace, it might be easier to see what is happening:

public List<Object__c> property { get; set; }

{
    // initialization block
    // this is the same syntax you use
}
2
  • I personally dislike this syntax-- that's what constructors are for. But, it's part of the language, and I will admit to abusing this feature from time to time, but it really goes against the entire OOP concept that Apex Code is trying to present.
    – sfdcfox
    May 26, 2016 at 3:21
  • 2
    I too find it distasteful. I've never found reason to use them myself.
    – Adrian Larson
    May 26, 2016 at 3:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .