Fix the bug: every handler reports the last channel
A deploy tool builds one notifier per alert channel up front, hands the list to
the scheduler, and the scheduler calls them later when a build finishes. It ran
for a month before anyone noticed every channel was reporting sms.
Nothing throws. The list holds three separate functions, exactly as intended,
and each one hands back a clean string. They just all hand back the same
string - the last one. Spot-check senders[-1]() and it looks perfect, which is
why this walks through review.
The mechanism is not what most people assume. A lambda does not capture the
value of name at the moment it is created. Its body does not run at all
then. It captures the variable name - the same one the loop keeps
reassigning - and reads it later, when it is finally called. All three lambdas
share that one variable, and by the time the scheduler calls them the loop has
long finished and left name set to "sms". These are not three functions that
each remembered a different channel. They are three functions looking in the same
box, and the box holds the last thing the loop put in it.
Your task: fix make_senders(channels) so senders[i]() returns
"alert sent to <channels[i]>" at every index, not just the last one.
You'll practice:
Reading three identical outputs as a bug rather than a coincidence
Binding a loop variable's current value into a closure instead of the variable itself
Show a hint
Show solution
Previous Next