Friday 26 August 2011

Protecting code from configuration

A few posts back, I talked about how you can use SObject in Apex to treat objects generically. For example rather than getting a field from Opportunity like this:

String name = myOpp.Some_Custom_Field__c;

You can use:

SObject mySObject = Opportunity.getSObjectType().newSObject();
String name = mySObject .get('Some_Custom_Field__c');

Whilst this opens interesting opportunities for code re-use, it can leave you exposed - what if someone changes the field's API name? In the first example, a user wouldn't be allowed to rename the API name field - salesforce.com would pick up that the field was referenced and prevent the change. In the SObject example however, this isn't the case - the field name is actually a string, so the change could be allowed and the first you'll hear of it is when your app starts breaking...

One way around this is to create a class that refers to the field directly, as in the first example. Seems a bit wasteful, to create a class just for this. We'll also need to write unit tests even though we're not really going to use the code.

Unless we skip the first part and just create a test class that refers to the field. Something like:

@istest
private class ConfigCheck {
static testmethod void testField {
Opportunity o = new Opportunity();
o.Some_Custom_Field__c = 'Test value';
}
}

This idea can be extended for all sorts of uses. My last post covered Record Types and raised the question: "What happens if someone renames a record type?". Write another test that checks for the presence of record types your code is expecting to be there. This won't prevent the record type name being changed, but if something goes wrong and you suspect config changes are to blame, you could run the tests in ConfigCheck to check your code's assumptions against the current configuration to see if anything has changed that will cause your code problems.

No comments:

Post a Comment