Our topic today is Dynamic Apex. In context, it allows you to dynamically reference objects and fields, Salesforce metadata, and permissions, etc. Dynamic programming languages have a lot of useful features. However, when we say “dynamic”, it usually means typing where variables do not have a fixed type.
For example, you can assign a value of one type to a variable and then later assign a value of another type to the same variable. The go-to example would be JavaScript. These programming languages even have frameworks that change how dynamic behavior operates or enforces static types.
Another feature is called “late binding”. The binding of method and function calls to their definitions and is done at runtime rather than at compile time. This means you can define methods and functions, modify the class structure, and add or delete methods from an object at runtime.
Dynamic languages often support what’s called “reflection” – a program that can modify itself by inspecting its own structure and behavior. For example, a program could iterate over its own functions, modify its own variables, or even generate new code at runtime. Let’s take a closer look!
What About Apex?
Apex is a statically typed object-oriented language, but it has dynamic programming language features. For example, you can build generic classes and methods which can work with any standard or custom object instead of hardcoding object names and fields.
This reusability factor is great and can be used for a generic data access layer that can query/insert/update any object, or even when integrating with external systems where integration logic can be subject to change.
Almost all Apex frameworks (or any Salesforce ISV product) will use dynamic features of the language. ISVs use it heavily to make their product widely available – they create packages and make them usable by any Salesforce org regardless of customization and metadata. An example here would be creating Apex methods and triggers that are dynamic in nature with the help of Tooling API.
Enterprise orgs use patterns and frameworks as well as dynamic Apex features for abstraction. This is so that changes in an org’s configuration will be reflected in code without changing the metadata.
Use Cases and Examples
Let’s take a look at simple but useful scenarios where Dynamic Apex can be used.
SOQL for Dynamic Queries
The code essentially retrieves all the values of the custom field Custom_Field__c from all records in the Account object and stores them in the records list. After the query is executed, you can then iterate through records to manipulate or examine the values of Custom_Field__c.
This is a common pattern for dynamically constructing a SOQL query in Apex based on predefined variables for the object and field names. You can also make the object names and field names dynamic by using custom metadata or custom settings through UI or programmatically.
Managing Permissions
Dynamic Apex enables you to check user permissions for accessing objects or fields.
A useful scenario for Dynamic Apex is where you can use Schema describe methods to check field-level security. You can programmatically determine whether the current user has access to the “Email” field on the “Contact” object in this example, which can be useful for enforcing field-level security in your org or application.
Retrieving Picklist Field Values
Let’s say you need to quickly retrieve both labels and API names of a picklist field when troubleshooting and – guess what – there are hundreds of picklist values.
Maybe someone put an emoji in an API name which is throwing an error (this may or may not have happened to me before!).
Regardless, whether you’re an admin or a developer, you can run Apex code in your org in the Anonymous Apex window – this can really help.
Handling Different Record Types
You can handle different record types dynamically and access their ID, API name,and Label, as well as other properties. It’s best practice to not hardcode IDs of your metadata if you like maintainability and less chance of errors.
Dynamic Component Generation in Visualforce
In this example, we are creating Visualforce datatable columns and setting their value dynamically using Apex. Apex supports dynamically creating Visualforce components and this is particularly useful when you need to implement complex UI behaviors that standard markup struggles to support.
Best Practices
- Security Considerations: Always ensure that user inputs are handled safely, especially when building dynamic queries, and beware that SOQL injection exists.
- Testing: Test all dynamic elements to prevent potential errors. This usually requires more code to test (sorry!).
- Performance Optimization: Evaluate and optimize the performance implications of using Dynamic Apex. It might not be required all the time!
Summary
Dynamic Apex offers a plethora of opportunities to Salesforce developers, enabling them to write code that’s both flexible and powerful. From managing permissions and building dynamic queries to building powerful frameworks, Dynamic Apex is an essential tool for modern Salesforce development.
The power of Dynamic Apex lies in its ability to adapt and respond to changing requirements without the need to alter the code structure. By understanding its features, use cases, and best practices, developers can leverage this feature to its full potential, creating applications that are robust, adaptable, and innovative.
If you’re looking to learn more about development or any topic about Salesforce, feel free to join me and others at SFXD, a community of Salesforce professionals. We currently have 10,000+ members, with a very active core membership connecting every day on our Discord server.
If you’re looking for an integration solution for your Salesforce org, I also recommend Declarative Webhooks which helps you easily build robust integrations between Salesforce and other platforms without code.
I hope you enjoyed this post and I will see you in the next one!