Review and Refactor
By the end of this lesson, you'll be able to:
- Review the complete feature for clarity and duplication
- Extract the repeated overlap-and-block logic into a shared private method
- Confirm the refactor preserves both overlap-detection scenarios
Prerequisites: "Test with Multiple Records"
Spotting the duplication
Looking back at Lesson 5's complete handler: both loops call datesOverlap(...) and then, if true, call addError() with a message — the exact same shape, just with a different pair of records and a different message each time. This is worth naming explicitly, even if extracting it fully would add a parameter for the message.
Extracting a shared check-and-block method
private void blockIfOverlapping(Leave_Request__c reqA, Leave_Request__c reqB, String errorMessage) {
Boolean sameEmployee = reqA.Employee_Name__c == reqB.Employee_Name__c;
Boolean overlaps = datesOverlap(reqA.Start_Date__c, reqA.End_Date__c, reqB.Start_Date__c, reqB.End_Date__c);
if (sameEmployee && overlaps) {
reqB.Start_Date__c.addError(errorMessage);
}
}
public void beforeInsert(List<Leave_Request__c> newRequests) {
// ... build employeeNames, query existingRequests exactly as before ...
for (Leave_Request__c newReq : newRequests) {
for (Leave_Request__c existing : existingRequests) {
blockIfOverlapping(newReq, existing, 'This leave request overlaps with an existing request.');
}
}
for (Integer i = 0; i < newRequests.size(); i++) {
for (Integer j = i + 1; j < newRequests.size(); j++) {
blockIfOverlapping(newRequests[i], newRequests[j], 'This request overlaps with another request in the same submission.');
}
}
}
blockIfOverlapping now holds the one piece of logic that was duplicated across both loops — each loop is left doing only what makes it genuinely different (which two Lists it's comparing), exactly the same refactoring instinct that closed out every previous project module in this course.
Confirming both scenarios still work
Re-running both of Lesson 6's Execute Anonymous verifications against this refactored version should produce identical results — the same two DmlExceptions blocked, the same success case allowed through. This is the whole point of refactoring, one final time: behavior unchanged, structure clearer.
Exercise
Call blockIfOverlapping for two given Leave_Request__c variables reqA and reqB, with the message "Overlap detected."
Show hint
blockIfOverlapping(reqA, reqB, "Overlap detected.");
Review and Refactor Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The closing lesson reviews the finished handler, noticing that both comparison loops repeat a very similar "check overlap, then addError" shape — worth extracting into one shared method.