Skip to main content

Code reviews rule: Constructor with side effects

Written by David Martin
Updated today

Constructor with side effects

Why is this an issue?

Performing DML operations (insert, update, delete, etc.) inside class constructors is considered bad practice. Reasons include:

  • Unexpected side effects: Creating an object instance should not modify the database. Callers don't expect new MyClass() to insert or update records, which makes the code harder to reason about

  • Governor limit risks: Each DML call counts toward Salesforce's per-transaction limits. If multiple instances are created in a loop, the constructor can quickly exhaust DML limits

  • Testing difficulties: You cannot construct the object without triggering the database write, making it harder to test other methods on the class in isolation

Examples

Example of incorrect code:

public class AccountProcessor {
public AccountProcessor(String accountName) {
Account acc = new Account(Name = accountName);
insert acc; // DML in constructor
}
}

Note: this rule also detects DML through method calls from the constructor:

public class AccountProcessor {
public AccountProcessor(String accountName) {
createAccount(accountName);
}

private void createAccount(String name) {
Account acc = new Account(Name = name);
insert acc;
}
}

Example of correct code:

public class AccountProcessor {
private String accountName;

// Constructor only stores state, no database writes
public AccountProcessor(String accountName) {
this.accountName = accountName;
}

// DML is moved to a separate method, called explicitly
// AccountProcessor processor = new AccountProcessor('Acme');
// processor.createAccount();
public void createAccount() {
Account acc = new Account(Name = this.accountName);
insert acc;
}
}

How can I fix violations?

Keep your constructor focused on setting up instance variables. Move the DML into a dedicated method like save() or createAccount() that callers invoke separately when they're ready to write to the database.

Resources

Did this answer your question?