Placing DML operations inside an Apex class constructor or initializer can cause unintended side effects. For example, simply loading a Visualforce page or initializing a component could automatically run inserts, updates, or deletes — modifying the database without any explicit user action. This makes the behavior unpredictable and potentially insecure. In contrast, performing SOQL queries in constructors or initializers is allowed, since queries do not modify data.
For example, consider the code below, accessing a page that references AccountHandler will cause a database insert, even if the user didn’t intend to create a record.
public class AccountHandler {
public AccountHandler() {
// Dangerous: Just initializing this class will insert a record
Account acc = new Account(Name = 'Auto Created');
insert acc;
}
}
Non-Compliant Code Examples
public class MyClass {
public MyClass() {
insert something;
}
}
Compliant Code Examples
public class MyClass {
public MyClass() {
// anything but a DML statement
}
}
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- apex-security # Rules to enforce Apex security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines