5

I thought these two samples would be functionally equivalent. But they behave differently:

  1. Initializing a property in the constructor:

    public with sharing class LeadController {
        public ApexPages.StandardController List {get; set;}
        public LeadController() {
            this.List = new ApexPages.StandardController(new Lead());
        }
    }
    

    (Works as expected. Super easy to manipulate the Lead from the Visualforce Page.)

  2. Initializing a property in the accessor:

    public with sharing class LeadController {
        public ApexPages.StandardController List {
            get {return List != null ? List : new ApexPages.StandardController(new Lead());}
            set;
        }
    }
    

    (Does not work. The state of the Lead goes missing in between form submissions.)

From a style point of view,the second example is preferable because the property is dealt from in exactly one place, as opposed to "cross cutting" into the constructor. But it misbehaves.

Can anyone explain why?

6

The syntax you need for the property to be initialized when first referenced (lazy initialization) is this:

public ApexPages.StandardController List {
    get {
        if (List == null) {
            List = new ApexPages.StandardController(new Lead());
        }
        return List;
    }
    set;
}

The code you show in the question never assigns a value to the List field.

| improve this answer | |

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.