I’ve once again had the pleasure over the past few days of using Custom Settings in Salesforce. I strangely enjoy using them; they are designed for a job and they do that job well. Well, that was how I felt until this most recent encounter with Custom Settings.

The difference this time was that I was using hierarchical settings rather than a list and I clearly hadn’t RTFM. As such I beat my head against the desk for a while whilst I got to grips with some, shall we say, curiosities? As I said this is probably all written elsewhere, I just wanted to make sure I made a personal note of it so next time I don’t get so frustrated.

The thing that had me stumped for the longest was the following piece of code.

  if(MySetting__c.getInstance(UserInfo.getUserId()) == null){
    MySetting__c val = new MySetting__c(Field_1__c=false, Field_2__c='a string');
    insert val;
  }

Obviously MySetting__c is my custom setting and I’m interested here in getting hold of the values for the current user. Of, or possible a red herring, another user has a MySetting__c record already. This if was part of a larger, more complex piece of functionality, and when I saw the method failing I naturally thought that the problem would never be in such a simple piece of code as this and spent some time trawling through the rest of the code. And yet I was clearly wrong this simple piece of code can fail – or at least not perform as I had expected.

In the land of list custom settings I would have been return a null if the record I have requested did not exist – a classic testing mistake that one: not setting up your custom data in your test scripts. However in this case, whilst the user had no record associated with them the if evaluated to false – it was returning a valid object. The interesting thing is the object return had Field_2__c set to null – this made life easier I would just change the if to test one of the fields on the returned object for null. Field_1__c was my choice (for some reason), it’s a Boolean but that didn’t matter, here on the Force.com platform a Boolean is a class not a type like other languages and as such can be null. Or at least that’s the case in all the other places I’ve come across Booleans on the platform. However here the Field_1__c was set to false and that’s no use as the real object can set this field to false. A quick switch to testing Field_2__c and everything was OK and behaving once again.

My lessons form this is little excursion are that a) hierarchical custom settings will return an object even when one isn’t defined for the User/Profile/Org combination or searching on and b) said object won’t necessarily be initialised as a normal object on the platform would be. Two worthwhile notes to remember as I’m not too sure how much more head banging my desk can take.