My Apologies to those who left comments on this blog post. I accidentally deleted it while creating a screencast on how easy it was to blog!
I’ve been playing with the neat new property syntax in Summer ’08. In many cases it provides a compressed syntax for writing tedious getters and setters.
Basically, instead of writing the following in a class:
we can now write this:
Many keystrokes saved. Note that the latter doesn’t actually generate a getProp()
method, see below.
Syntax examples
That’s actually an abbreviated abbreviated syntax. The get and set can be expanded somewhat to contain custom code. For example:
A couple of things to note here:
- The
get
body must end in areturn
, sensibly… - The
put
body receives an implicit argument calledvalue
of the same data type as the property.
You can also omit a get or a set, in which case the property becomes write or read only, respectively.
Here are some more valid examples:
The last one assumes we have a getFox()
. The Apex Language Reference Documentation actually says about the get
method: “You cannot call another class or method. The flow of the script cannot leave the accessor body.” But as you can see from the example above, my get
does leave the body and it still appears to work. So I’m not sure what’s going on here.
Properties vs Getters/Setters
Another interesting thing to note is that these are properties, these aren’t a nice shorthand for writing a getProp(), setProp()
pair. Actually, any call to getProp()
will fail – that method doesn’t exist.
You access the property by name, ie. Foo.prop
will call the getter or setter depending on context.
Visualforce interactions
I found an interesting Visualforce interaction. In a Visualforce page you can have something like
This makes an implicit call to the method getMustRender()
. In fact, the editor suggests creating such a method if it doesn’t exist in the controller. Interestingly, you can also define a property in the controller instead, ie.:
Now the Visualforce page will work just fine, even though there is no getMustRender()
method. Obviously it’s enough for the property to exist.
This example highlighted something I wish I could do with these properties: set default values. I want the property to default to true, but I couldn’t find a way to do that with the syntax. I can imagine something like:
🙂
Technorati Tags:
visualforce,
apex