0% found this document useful (0 votes)
3 views9 pages

Trigger Code Review

The document outlines various high, medium, and low priority issues across multiple triggers in Salesforce Apex code, focusing on bulk safety, error handling, and code quality improvements. High priority concerns include the need for bulk-safe SOQL queries, DML operations, and proper error handling in trigger contexts. Medium and low priority issues address code readability, optimization, and adherence to best practices in naming conventions and structure.

Uploaded by

Yeshwanth
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Trigger Code Review

The document outlines various high, medium, and low priority issues across multiple triggers in Salesforce Apex code, focusing on bulk safety, error handling, and code quality improvements. High priority concerns include the need for bulk-safe SOQL queries, DML operations, and proper error handling in trigger contexts. Medium and low priority issues address code readability, optimization, and adherence to best practices in naming conventions and structure.

Uploaded by

Yeshwanth
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CP_BargeReleaseTrigger —

High Priority
● SOQL Queries Not Bulk-Safe – fetchOrderDetails(String orderNumber)
(lines 57–62) and handleOrderUpdate(String BargeID) (lines 107–108) each
query a single record; both must be refactored to accept Set<String> / Set<Id>
parameters and query with IN to support bulk trigger contexts.
● DML Statements Not Bulkified – Lines 95 and 115 call update b on individual
records; must collect records into a List<> and perform a single update
recordsToUpdate after the loop.
● Hard-coded Destination Strings – Lines 16, 21, 26, 42, 44, 45, 110, 113, 114
compare directly against destination names like 'Growmark, Cincinnati, OH';
must be extracted to a Constants class with named final String fields.
● Missing Error Handling – Trigger sections (lines 8–64) have no try-catch; failures
cause silent partial rollbacks; must wrap each trigger context block with try-catch and
use [Link](message) for user-facing feedback.

Medium Priority
● @future Method Processes Single Record – fetchOrderDetails(String
orderNumber) is a @future method that handles one order at a time; should
accept Set<String> orderNumbers to process bulk records in a single
asynchronous invocation.
● [Link] Statements in Production – Lines 12, 29, 72, 87, 89, 91, 106, 112
have debug logs; must be removed or wrapped with [Link]
conditional.
● String Comparison Using == and != – Lines 13, 30, 45, 57 compare strings with
==/!= against ''; should use [Link]() and [Link]()
throughout.

Low Priority
● No Method Documentation – Helper methods lack @description, @param, and
@return comments.
● Inline null + empty checks – b.LF_Destination__c != null &&
b.LF_Destination__c != '' repeated in multiple places; should use
isNotBlank() / isBlank() private utility methods.

CP_ContactTrigger —
High Priority
● Potential ListIndexOutOfBoundsException – Line 22 accesses
usIdsLst1[0] without checking if the list is non-empty; must add if(!
[Link]()) before constructing the batch.

Medium Priority
● Unused SOQL Fields – Line 15 queries [Link],
[Link], ProfileId, and [Link] through the User
relationship, none of which are used in the logic; must be removed to reduce query
overhead.
● Redundant Null Check – Line 13 checks !
[Link]() && consToTriggerIntegration
!= null; since isEmpty() would throw a NullPointerException if null, the null
check should come first or isEmpty() alone is sufficient after a prior null guard.
● Unnecessary List Building – Lines 16–19 build usIdsLst1 just to use
usIdsLst1[0]; should directly use usrs[0].Id after the empty check.
● Missing Error Handling on Batch Execution – [Link]() on
line 23 is not wrapped in try-catch; should add a catch block with [Link].

Low Priority
● Abbreviated Variable Names – usrs and us on lines 15, 17 should be users and
user for readability.
● Magic Number for Batch Size – Hard-coded 1 on line 23 should be a named final
Integer DEFAULT_BATCH_SIZE = 1 constant with a comment explaining why
batch size 1 is intentional.

CP_EmailMessageTrigger —
High Priority
(No blocking runtime bugs; see medium for functional issues)

Medium Priority
● Hungarian Notation Variable Names – mapCases, mapCaseOwnerIds, objEM,
objC on lines 2, 3, 5, 12, 17, 20, 26, 27 use prefixes and abbreviations; should be
renamed cases, caseOwnerIds, emailMessage, caseRecord.
● Magic String '500' for Case ID Prefix – Lines 6 and 18 use indexOf('500')
== 0 to identify Case records; should extract to private static final String
CASE_ID_PREFIX = '500' and use startsWith() instead of indexOf().
● Magic String 'ref:' as Inline Literal – Line 19 uses 'ref:' directly; should be
private static final String REF_PREFIX = 'ref:'.
● Lowercase SOQL Keywords – Line 12 has select Id,OwnerId from Case
where Id IN; must capitalize all SOQL keywords (SELECT, FROM, WHERE).

Low Priority
● [Link] Should Be [Link] – Lines 5 and 17 use lowercase
[Link]; Apex convention capitalizes trigger context variables as
[Link].
● Explicit Boolean Comparison – No instances found in the provided code, but the
pattern == false should be replaced with ! throughout.

CP_FeedItemTrigger —
High Priority
● Hard-coded '500' ID Prefix for Case Detection – Line 6 uses
[Link]([Link]).indexOf('500') == 0 which is
fragile; must replace with [Link]() ==
[Link] for type-safe record identification.
● Missing Exception Handling on DML – The update [Link]() call
has no try-catch; a DmlException would roll back the transaction without meaningful
feedback; must wrap in try-catch with a [Link] log.

Medium Priority
● Explicit == false Boolean Comparison – Line 11 uses
[Link]() == false; should be !
[Link]().
● Commented-Out Conditions – Lines 11 and 16 have commented
[Link]() and old ID prefix checks inline; must be deleted.
● Redundant Null Check Before containsKey() – Line 16 checks
[Link] != null before
[Link]([Link]); since the key was only
added when non-null, the null check is redundant.

Low Priority
● Hungarian Notation Variable Names – objItem, objC, mapCases,
mapCaseOwnerIds should be renamed feedItem, caseRecord,
casesToUpdate, caseOwnerMap.
● Lowercase [Link] – Should be [Link] following Apex conventions.
● Lowercase SOQL Keywords – select Id,OwnerId from Case where Id
IN should use uppercase keywords.

CP_LeadTrigger —
High Priority
● SOQL Query Inside Loop – Line 43 of [Link] has a SOQL
query inside a for loop; must be moved outside the loop using a pre-built Set<Id>
and an IN query, storing results in a Map keyed by ID.
● DML Statements Inside Loop – Lines 71 and 75 of [Link]
have insert/update DML inside loops; must collect records into lists and perform
single bulk DML operations outside the loop.

Medium Priority
● Excessive afterUpdate() Method Length – Lines 1–73 of the method mix lead
filtering, account map building, contact record type lookup, and contact creation;
must be decomposed into filterConvertedLeads(), buildAccountMap(),
getContactRecordTypes(), and buildContactsList().
● Missing Braces on Single-Line if Statements – Lines 43 and 47 have if without
braces; must add curly braces to all control statements.
● Large Commented-Out Code Block – Lines 2–6 have a commented class-level
property block, and several commented statements throughout; all must be removed.

Low Priority
● Hungarian Notation Variable Names – lstContacts, mapOld, mapLeads,
objLead, mapContactRecordTypes should be contacts, oldLeadMap,
convertedLeads, lead, contactRecordTypes.
● Missing Null Check at Method Entry – afterUpdate() should validate leads !
= null && ![Link]() before processing.
● Class Could Be More Descriptive – AddRelatedRecord could be renamed
LeadConversionRelatedRecordHandler to better express its purpose.

Now let me read the two remaining uploaded files I haven't seen [Link] I have all the
content. Here are all the summaries:

WorkflowTrackerTrigger —
High Priority
● Apex: URL Construction Without Validation – Helper line dat['Link'] = '/'
+ [Link] builds a URL without validating the Salesforce record ID format;
must add a /^[a-zA-Z0-9]{15,18}$/.test([Link]) guard before
constructing the link.
● Apex: Missing Error Handling on @AuraEnabled Methods – getRecords() and
other @AuraEnabled methods have no try-catch; an unhandled QueryException
or general Exception will surface as an unhelpful error to the UI; must wrap with
try-catch returning a safe empty list.

Medium Priority
● Apex: SOQL Query Not Fully Optimized – Lines 30–40 build UserIdsSet from
GroupMember then immediately query Group using those IDs; should pre-build a
groupIds set during the first loop to reduce the second query's filtering.
● Apex: Hard-coded Role, Profile, and Status Strings – Strings like 'Account
Specialist Manager', 'System Administrator', 'Legal Agreement'
scattered across lines 59–62; must be extracted to a
WorkflowTrackerConstants class.
● Apex: Unused roleName Variable – Lines 80–82 declare roleName inside an if
block but never use it in the dynamic query; should be moved outside the block and
used conditionally.
● JS: Inefficient for Loop for Search Filtering – Lines 120–158 of the controller use
a for(i=0; i < [Link]; i++) with indexOf; should use
[Link]() with .includes().
● JS: Duplicate Pagination Logic – onNext and onPrev handlers repeat the same
currentPageNumber get/set pattern; should use a shared
navigateToPage(component, pageNumber) helper.
● JS Helper: Inefficient Data Transformation Loop – Lines 23–51 use for...of
with multiple conditional assignments and push; should use [Link]() with
object spread.

Low Priority
● JS: [Link] in Production – Multiple [Link] calls in controller and
helper files; should be removed or gated behind a debug flag.
● JS Helper: Sort Function Missing Null Handling – Lines 91–111 sort comparator
doesn't handle null/undefined values; should add null guards before comparison.
● CSS: Magic Numbers – Hard-coded 55%, 40%, 50px, -20px, 320px should use
CSS custom properties.
● Aura Markup: Commented Dead Code – Old commented-out lightning:input
blocks should be removed entirely.
● Aura Markup: Nested aura:if Complexity – Multiple layers of nested
conditionals; should restructure with isLoaded as the outer condition.
● Apex: [Link]() Should Be Used – String comparisons with == in Apex
should use .equals() for proper null-safe comparison.
AddRelatedRecordTrigger —
High Priority
(No high-priority runtime bugs identified; see medium below)

Medium Priority
● Potential Null on [Link](objRC.lead__c) – Line 67
accesses the map without verifying the key exists; if the lead has no converted
contact, RecordTypeId will silently be assigned null; must use
[Link](objRC.lead__c) ? ... : null.
● Missing Error Handling on DML Operations – Lines 76–77 and 80–81 perform
update and insert without try-catch; a DmlException will roll back the
transaction without context; must wrap each in try-catch with [Link].
● Parent Relationship Traversal in SOQL Unnecessary – Line 52 queries
Lead__r.Entered_In_Promise__c through the relationship, but the mapLeads
map already contains that data; should remove the relationship traversal and use
[Link](objRC.Lead__c) directly.

Low Priority
● Redundant containsKey Check – Line 49 checks
[Link]([Link]) inside a loop that
already queries records from that keyset; the check is guaranteed true and should be
removed.
● Commented-Out Code – Lines 27 and 82–83 have commented
lstContactsToDelete logic; must be deleted.
● Hungarian Notation Variable Names – lstContacts, lstContactsToDelete,
mapLeads, mapAccounts, mapContactRecordTypes should be contacts,
contactsToDelete, leadsMap, accountsMap, contactRecordTypesMap.
● Magic Strings – 'All_Qualified_Leads' and 'Active' on lines 24 and 68
should be private static final String constants.

BargeReleaseTrigger (second analysis


document) —
High Priority
● Missing Error Handling on Helper Method Calls – All four trigger context sections
call BargeReleaseTriggerHelper methods without try-catch; should wrap each
in try-catch and use [Link] for failures.

Medium Priority
● [Link] in Production – Lines 12 and 29 of the trigger log
LF_Destination__c values; must be removed.
● Redundant String Null + Empty Checks – Lines 13, 30, 45, 57 use
b.LF_Destination__c != null && b.LF_Destination__c != '' and
similar patterns; should use [Link]() and [Link]()
throughout.
● Repeated [Link]([Link]) Calls – Lines 30 and 57 call
[Link]([Link]) multiple times in the same loop body; should store
result in a local oldRecord variable.
● Duplicate Iteration/Filter Patterns – The same for...new + collect pattern
appears in all four trigger contexts; should extract a
filterRecordsWithDestination(records) helper to reduce duplication.

Low Priority
● Missing Early Exit Guard – No early return if [Link] is null or empty at the
start of the trigger; should add if ([Link] == null ||
[Link]()) return;.

CaseTrigger —
High Priority
(No high priority runtime bugs identified)

Medium Priority
● Inconsistent Trigger Context Property Casing – [Link] and
[Link] on multiple lines use PascalCase; Apex convention requires
lowercase [Link] and [Link]; must be corrected
throughout.
● Missing Null Checks – [Link] and [Link] should be validated
before passing to handler methods; should add [Link] != null guards.

Low Priority
● Inconsistent Brace Style – Some if blocks use Allman style (opening brace on
next line) while others use K&R style; should standardize to K&R (opening brace on
same line).
● Missing Space After Commas in Method Calls –
[Link]([Link],[Link]
ap) is missing a space; should be [Link], [Link].
● Inconsistent Comment Formatting – //Added as part of ADO-32674 and
//shailender 06-october-2025 lack spaces and consistent date format;
should be // Added as part of ADO-32674 with standard date format.
● ADO Reference in Production Code – Work item references like ADO-32674
should be replaced with business context comments in production code.

ContactTrigger (second analysis


document) —
High Priority
(Same core issues as the first ContactTrigger analysis; key additions below)

Medium Priority
● Logic Embedded Directly in Trigger – All processing logic is inline in the trigger
rather than a handler class; should extract to
[Link]([Link]) for
testability.
● High Cyclomatic Complexity – Nested conditions and loops in the trigger body
reduce readability; should extract filterApprovedContacts() and
hasApprovedContacts() helper methods.
● usIdsLst1 List Built But Only [0] Used – The entire user ID list is populated but
only the first element is consumed; should either use usrs[0].Id directly or modify
the batch class to accept a list.
● CRUD Permissions Not Checked Before SOQL –
[Link]() is not verified before querying
the User object; should add a permission check.

Low Priority
● Variable Names usrs, us, usIdsLst1 – Should be users, user, userIds.
● consToTriggerIntegration – While descriptive, could be shortened to
contactsForIntegration for brevity.
● Null Check Order – ![Link]() &&
consToTriggerIntegration != null has the wrong order; null check must
come first.
RemoveWhoIdFromContractActivityTrig
ger —
High Priority
● Unused SOQL Query Consuming Governor Limits – Lines 4–5 declare
List<Task> re and run [SELECT id,WhatId,WhoId FROM task LIMIT 1]
that is never used in any business logic; must be removed to conserve SOQL
governor limits on every trigger invocation.
● [Link] Statements in Production – Lines 8–9 debug [Link] and
[Link] in the loop; must be removed.

Medium Priority
● Business Logic Embedded in Trigger – All logic is inline rather than delegated to a
handler class; should extract to
[Link]([Link]) for
better organization and testability.
● Missing Error Handling on DML – update tasksToUpdate has no try-catch;
should wrap with try { update tasksToUpdate; } catch(Exception e) {
[Link](...); }.
● Hard-coded Contract Key Prefix '800' – Line 13 uses startsWith('800') to
identify Contract records; should use
[Link]() stored as private
static final String CONTRACT_KEY_PREFIX.

Low Priority
● Inconsistent Formatting – Line 4 has new List<Task>() with extra spaces;
should be new List<Task>().
● Missing ApexDoc Comments – No @description, @param, or @return
documentation on the trigger or any extracted methods.

You might also like