Friday, May 22, 2009

public string bar { get; set; }

In the old days, I used to write code in VC++ 6.0, and my properties would look like this:

public class foo
{
private string bar;
public string getBar()
{
return bar;
}
public void setBar(string value)
{
bar = value;
}
}

Then, about 6 million years ago, .Net allowed us to use getters and setters and the code would look like this:

public string bar { get; set; }

Much nicer... cleaner and easier to read, less tedious to write... everyone's a winner, baby.


Now, when I write code in Apex - salesforce.com's very own development language (not quite java, not quite .Net, not quite good enough) - I instinctively use the latter syntax, especially given that elsewhere in the code base, usage of the properties are fully supported, 

eg. 
foo.bar = "Beyond All Recognition";
string b = foo.bar;

Now; In a VisualForce page, one binds to values in a controller class, using the following syntax:

<apex:page controller="foo">
  <apex:outputText value="{!bar}" />
</apex:page>


So the page needs to be able to see 'bar' from the controller, foo. But we've exposed bar through a public getter, so we'll be fine, right?
WRONG!

No, we need to explicitly write a public method that returns bar as a string. 
Always? Nope, not always - sometimes the getter property will be fine. 
And what will happen if the page can't see the property? Anything... literally anything... I wasted 8 hours last week chasing one of these because the string I was trying to show on the page was not exposed explicitly by a public string getBar() method, and the page, when rendered, helpfully told me 'This URL no longer exists... your bookmark may be out of date or you may be a half-wit. Thanks for using Salesforce!" (or similar)

Coincidentally, on another 'URRGGHH!! IT SHOULD WORK!!!" problem I was having last week, I had written a page that loaded a few defaults, then allowed the user to tweak the values they wanted and press 'submit' when they were happy... But I foolishly didn't write a getBar() method, and the 'submit' button was happily reloading the defaults immediately before sending the values off to the database...


So Monday morning beckons, and I know it will be filled with refactoring, retesting, refactoring, and more retesting...

No comments:

Post a Comment