Apex Data Write in Constructor
Why is this an issue?
Performing DML operations (insert, update, delete, etc.) inside class constructors is considered poor practice because:
Testing difficulties: Constructors run before test setup can mock or control database state
Unexpected side effects: Creating an object instance should not cause database changes
Governor limit risks: If many instances are created, DML limits may be exceeded
Error handling complexity: Exceptions during construction leave objects in undefined states
Examples
Example of incorrect code:
public class AccountProcessor {
public AccountProcessor(String accountName) {
Account acc = new Account(Name = accountName);
insert acc; // DML in constructor
}
}
Example of correct code:
public class AccountProcessor {
private String accountName;
public AccountProcessor(String accountName) {
this.accountName = accountName;
}
public Account createAccount() {
Account acc = new Account(Name = this.accountName);
insert acc;
return acc;
}
}
How can I fix violations?
Move the DML operation to a separate method that can be called after construction:
Store necessary data in instance variables during construction
Create a dedicated method (e.g.,
save(),execute(),process()) for the DML operationCall this method explicitly when database operations are needed
When should I disable this rule?
You may want to dismiss this issue if:
The class is specifically designed as a one-shot processor where construction and execution are intentionally combined
The constructor is only called in controlled circumstances where side effects are expected
Resources
