1

I was wondering what your thoughts/concerns are regarding to refering to a property itself in your getter/setter... Is this considered to be always save and correct in apex?

Example:

private String stringVar{
    get{
        if (stringVar == null){
            stringVar = someValue;
        }
        return stringVar;
    }
    set{stringVar = value;}
}

This works perfectly in apex. Some programming languages however avoid this by refering to a field value in the getter and setter like this:

private String _stringVar;
private String stringVar{
    get{
        if (_stringVar == null){
            _stringVar = someValue;
        }
        return _stringVar;
    }
    set{_stringVar = value;}
}

1 Answer 1

3

Yes, the method of storing data as in the first example is outlined in the documentation, and fully supported. Other languages have the limitation of needing a backing variable simply because the symbols used for get and set are functions, while in Apex, the getter and setter methods are defined in addition to the variable itself. This allows developers to write more efficient code, since they don't need to declare separate backing variables to store the data.

3
  • Thanks @sfdcfox! Do you happen to have a link to this documentation? Apr 29 at 12:09
  • @PieterJacob It's explained in detail in Apex Properties.
    – sfdcfox
    Apr 29 at 15:46
  • thanks a lot! I appreciate it. Have yourself a nice week! May 1 at 7:12

You must log in to answer this question.

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