Find your content:

Search form

You are here

Read-only and write-only automatic properties

 
Share

The Force.com Apex Code Developer's Guide documentation for Apex Properties:Using Automatic Properties contains the following:

Properties do not require additional code in their get or set accessor code blocks. Instead, you can leave get and set accessor code blocks empty to define an automatic property. Automatic properties allow you to write more compact code that is easier to debug and maintain. They can be declared as read-only, read-write, or write-only. The following example creates three automatic properties:

public class AutomaticProperty {
   public integer MyReadOnlyProp { get; }
   public double MyReadWriteProp { get; set; }
   public string MyWriteOnlyProp { set; }
}

This had me scratching my head a bit. MyReadWriteProp makes perfect sense. The usefulness of MyReadOnlyProp and MyWriteOnlyProp eludes me.

Why would you want a read-only or write-only automatic property?

As far as I can tell you could never actually do anything useful with them. Either you could read a value that you could never set or write a value that you could never read.

Am I missing something or is this just a poor example in the documentation? Maybe there is some way to access the automatically generated backing property to set/read the value?


Attribution to: Daniel Ballinger

Possible Suggestion/Solution #1

Adding access modifiers to the getters and setters for MyReadOnlyProp and MyWriteOnlyProp allows them to be read/written to from within the class.

Expanding upon Daniel Blackhall's answer:

public class AutomaticProperty {
    public integer MyReadOnlyProp { public get; private set; }
    public double MyReadWriteProp { get; set; }
    public string MyWriteOnlyProp { private get; public set; }

    public AutomaticProperty() {
        this.MyReadOnlyProp = 25;
        ...
    }

}

Attribution to: Brian

Possible Suggestion/Solution #2

You are correct, this a badly written example, you can still set the values within the class. e.g

public class AutomaticProperty {
    public integer MyReadOnlyProp { get; private set; }
    public double MyReadWriteProp { get; set; }
    public string MyWriteOnlyProp { private get; set; }

    public AutomaticProperty() {
        this.MyReadOnlyProp = 25;
        ...
    }

}

This means at least in the controller context MyReadOnlyProp could be used as an outputText. There are plenty of other uses I won't go into unless you're interested


Attribution to: Daniel Blackhall
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4471

My Block Status

My Block Content