Intermediate 25 min read

Handle Edge Cases

By the end of this lesson, you'll be able to:

  • Guard getEmployee against a missing ID returning null unexpectedly
  • Guard addEmployee against a null Employee argument
  • Distinguish "not found" from "invalid input" as two different edge cases

Prerequisites: "Generate Reports from Collections"

Handling a missing employee ID

public Employee getEmployee(String employeeId) {
    if (! employeesById.containsKey(employeeId)) {
        System.debug('No employee found with ID ' + employeeId);
        return null;
    }
    return employeesById.get(employeeId);
}

Without this check, calling getEmployee('E999') for a nonexistent ID would already return null silently (recall Module 16's "Maps" lesson) — but adding the explicit check here means the reason is logged clearly, rather than a caller discovering a mysterious null further down the line with no explanation.

Guarding against a null Employee

public Boolean addEmployee(Employee emp) {
    if (emp == null) {
        System.debug('Cannot add a null employee.');
        return false;
    }
    if (employeesById.containsKey(emp.getEmployeeId())) {
        return false;
    }
    employeesById.put(emp.getEmployeeId(), emp);
    return true;
}

Without this guard, emp.getEmployeeId() on a null emp would throw a NullPointerException — exactly the failure mode from Module 13's "Common Built-In Exceptions" lesson. Checking emp == null first turns a crash into a clean, logged rejection.

Two different kinds of edge case

  • "Not found" (a valid lookup that simply has no match) is an expected outcome — a normal part of using the directory. Returning null with a clear debug message is enough.
  • "Invalid input" (a null Employee, or one with a blank employee ID) is a programming mistake on the caller's part — still handled without crashing, but worth treating as a more serious signal that something upstream is wrong.

Both get handled gracefully here, but recognizing the difference helps decide, in later modules, when a situation is serious enough to warrant a custom exception (Module 13) instead of just a false return value.

Exercise

Add a validation check to addEmployee rejecting an Employee whose getEmployeeId() is null or an empty String.

Show hint

String.isBlank(emp.getEmployeeId())

APEX

Handle Edge Cases Quiz

1. What is the difference between "not found" and "invalid input" as edge cases?

Log in to submit the quiz and save your score.

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

This lesson hardens the directory against two distinct edge cases — a lookup for an ID that doesn't exist, and an attempt to add a null Employee — following the same guard-clause discipline as Module 12.