I am a big fan of writing code that generates no runtime errors. This is an implementation of a function that takes the first element of an array.
1 2 3 4 5 6 |
|
This is the standard way we are taught to write programs. However, there is another way to write this function that makes the exception unneccessary.
1 2 3 4 5 6 7 8 9 |
|
Suddenly the program flow is dictated by the emptiness of the array. Besides knowing well that this function will never throw an exception, the program that uses it will be structured in such a way that you can guarantee within the scope of the returnCallback function that was passed in, the function will always have the first element of the array. You don’t even have to check for nullness.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
And as a perk, if this function compiles, you know that it will run without errors.