rspec/rules/S5376/apex/rule.adoc

61 lines
1.7 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
An Apex trigger may be called with a batch of records. This for example happens when a bulk DML is executed. All records provided by the triggers should be processed.
This rule raises an issue when specific records from the ``++Trigger++`` are referenced, i.e. when it finds one of the following patterns:
* ``++Trigger.new[x]++``
* ``++Trigger.old[x]++``
* ``++Trigger.oldmap.get(x)++``
* ``++Trigger.newmap.get(x)++``
where ``++x++`` is a hardcoded number.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,apex]
2021-04-28 16:49:39 +02:00
----
trigger CaseTrigger on Case (before insert, before update) {
//This only handles the first record in the Trigger.new collection
//But if more than 1 Case initiated this trigger, those additional records
//will not be processed
Case c1 = Trigger.old[0]; // Noncompliant
Case c2 = Trigger.new[0]; // Noncompliant
Case c3 = Trigger.oldmap.get(1); // Noncompliant
Case c4 = Trigger.newmap.get(1); // Noncompliant
// ...
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,apex]
2021-04-28 16:49:39 +02:00
----
trigger CaseTrigger on Case (before insert, before update) {
List<String> Names = new List<String>{};
//Loop through all records in the Trigger.new collection
for(Case c: Trigger.new){ // Good: Iterate through the trigger.new array instead
c.Subject = c.Number + ':' + c.Status
}
}
----
2021-04-28 16:49:39 +02:00
== See
* https://trailhead.salesforce.com/en/content/learn/modules/apex_triggers/apex_triggers_bulk[Bulk Apex Triggers]
* https://developer.salesforce.com/wiki/apex_code_best_practices[Apex Design Best Practices]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]