Apex Controllers: What do the get; set; do?

  • I've built a few apex controllers, and like most people have copied some code from here and there. In the controllers, there's typically an expression that looks like the following:

    public *var type* someName {get; set;}
    

    Initially I thought I needed to supply a function to the get part if the VF page was grabbing data, something like so:

    get = getData(); set;
    
    public function string getData(){
        return 'data!';
    }
    

    And the opposite for set (if users were inputting data). But now I see my controllers work perfectly well just having the top expression as {get;set;}.

    I've looked through the salesforce docs and I've read all the parts regarding creating custom controllers - I see the get; set; being referenced, but nowhere explaining what this part does and how I can use it.

    Have you come across any docs on what this part does and how I can use it?

    Thank you all!

    Zac

  • sfdcfox

    sfdcfox Correct answer

    6 years ago

    Visualforce requires a "getter" and "setter" to reference a variable in the controller or extension. Without a getter or setter, even public or global variables cannot be referenced in Visualforce expressions.

    "get;" is basically: public *datatype* getVarName() { return varName; }

    "set;" is basically: public void setVarName(*datatype* value) { varName = value; }

    There are subtle differences though. For example, the function doesn't actually exist; it's called implicitly.

    You can make variables read-only by not including set;, and you can make them write-only by not including get;.

    Inside Apex Code, you can also use these to control readability and writeability.

    For example:

    public static Integer counter {
        get { if(counter == null) counter = 0; counter++; return counter; }
        private set; }
    

    This counter increases by 1 each time it's used, but can't be set outside of the class that contains it.

    public class OtherClass {
       public void someMethod() {
           System.debug(FirstClass.counter);
           System.debug(FirstClass.counter);
           FirstClass.counter = 10; // Compiler error
       }
    }
    

    Without the compiler error, it would debug 0, then 1.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM