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?

1 Answer 1

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.

0

You must log in to answer this question.

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