We can define a Custom Metadata Type with fields to relate to a paricular object in the system, and to a particular field within that object via the Metadata Relationship type of field. It would be really useful to be able to define a Metadata Relationship field that picks Apex Classes in order to support designs that use dependency injection.
For example, consider using custom metadata to define how records in Salesforce need to be rearranged to be sent to an external system in JSON format. I typically define a Custom Metadata Type which describes how to convert each field. It has 4 fields:
Salesforce_Object__c: Metadata relationship to entity definition
Salesforce_Field__c: Metadata relationshup to field definition
External_Field__c: Text defining what to call the field in the JSON output
Converter_Class__c: Text (would like this to be a metadata relationship) defining a class to use to convert the data
In Apex, we then use Type.forName() to load the Converter_Class__c, and cast it to a known interface. This class can then be used to do type conversion in an extensible way e.g. convert Date/Time to whatever string the system wants, or currency from pounds in Salesforce to pennies in the external system.
This approach is likely to become more popular due to efforts like Andrew Fawcett's dependency injection library.
If the Custom Metadata Type allowed us to refer to the Apex Class directly, rather than by recording it in a string, then this would have a number of benefits:
- No typos in the class name
- An explicit metadata reference between the two, so
- The class can be picked up as required by deployment tools when they deploy the metadata record
- The class will be seen as required when packaging
- Analysis tools would be able to see that the class is used, even though it is not explicitly created in code
- Generally, encouraging people to use this pattern where appropriate, which makes for better code