The Election Day exercise stresses the importance of checking for nil pointers.
A note of caution however: always check if a pointer is not nil before dereferencing. Dereferencing a nil pointer will make the program crash at runtime!
However, the tests do not enforce this. The TestIncremenetVoteCount and TestDisplayResult tests do not verify that a nil pointer is handled properly.
It would useful to put this advice to practice by adding the nil pointer test cases to this exercise.
The exercise currently requires a null check in the counter for the VoteCount
function.
Adding a nil test case for IncrementVoteCount
, would mean that solutions that assign a value via the pointer (*a = ...
) like shown in the examples will not work, which I think it’s a shame.
For DisplayResult
, I guess the message could be different in case the input is a nil
pointer, but I’m not sure adding that test case adds much value, since the student already proved it can handle the nil case in the VoteCount
function.
One of the challenges with this exercise is that takes into account that errors were not taught yet in this point in the track. Meaning that changes to exercise like “return an error when there is a nil pointer here” would be something “real code” would probably do, but were left out of the exercise intentionally because errors were not shown to the student at this point. But it’s something mentors can talk with students.