rspec/rules/S5376/apex/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

66 lines
1.7 KiB
Plaintext

== Why is this an issue?
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.
=== Noncompliant code example
[source,apex]
----
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
// ...
}
----
=== Compliant solution
[source,apex]
----
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
}
}
----
== Resources
* 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)
=== Message
Iterate over Trigger's records to process them all.
endif::env-github,rspecator-view[]