An Apex trigger is failing due to a 'System.LimitException: Too many DML statements: 151'. What is the optimal refactoring approach?
Bulkification is the core design pattern for Salesforce development. Moving DML outside the loop ensures that only one DML statement is used regardless of the number of records, which completely eliminates the 'Too many DML statements' error and makes the code scalable and highly performant.
Why this answer
The error clearly indicates the failure to bulkify DML. The solution is to collect all records needing updates into a single list and perform one DML statement after the loop. This reduces 150+ individual operations to one, keeping the code within governor limits and significantly improving performance by reducing the number of round-trips to the database during the transaction processing cycle.
Exam trap
Candidates often mistakenly attempt to fix the error by increasing the batch size or splitting the code into multiple triggers, rather than addressing the core lack of bulkification.