Daily Learnings: Tue, Mar 21, 2023
Discovery consists of seeing what everybody has seen and thinking what nobody else has thought. — Jonathan Swift
Notes on Programmatic Configuration in Salesforce
Some notes on programmatic configuration tools available on the Salesforce platform to assist with building more metadata-driven applications. Taken from Advanced Apex Programming.
- Custom Metadata Learnings
- Cannot be edited, created, or deleted as part of Unit Tests
- Can be easily read in Apex, but definitely not easily updated via Apex
- If you have the need to have custom UI screens for your users to manage configuration, generally advisable to use Custom Settings instead
- Custom Metadata requires that the user doing the updates have access to the
Manage Metadata via APIpermission (i.e., must almost basically be a System Admin)- This is since you have to do a MetadataAPI call to CRUD Custom Metadata via Apex
- Is generally a good choice for internal projects, but not for packages that you’ll be distributing
- Note: I’ve personally seen this multiple times in building managed packages for clients to distribute on the AppExchange. It might not always be the case, but as of the time of this writing, it definitely has burned me in the past to try and use Custom Metadata Types over Custom Settings.
- Actual values of Custom Metadata can be much more easily deployed from org to org than Custom Settings
- Can be both a pro and a con (con is that maybe you don’t actually WANT to deploy configuration changes between environments)
- Custom List Settings
- CAN be enabled in an org still, but you have to go and find the setting to enable them
- Can be easily edited, created, or deleted in Apex
- Apex has automatic access to all Custom Settings in the given namespace
- Exact settings/values set in an org cannot be deployed
- Best Practice: ALWAYS wrap all configuration / custom setting / custom metadata interactions in their own Apex class
- Have getters / setters for each custom field / attribute which encapsulates the logic of accessing / setting
- This makes it a lot easier in writing unit tests
- Also centralizes logic
- See example code for more specific handling for edge cases