4 ms·
There are many scenarios in dynamic languages where an "incorrect" (i.e. unexpected) type could be provided, but the program would not crash and potentially pro
by michaelmior 5y ago
There are many scenarios in dynamic languages where an "incorrect" (i.e. unexpected) type could be provided, but the program would not crash and potentially produce incorrect results or at the very least, hide where the real error occurs.
For example, assume you have Python code to sum up an array (yes, I know there's a builtin, but it's an easy example):
def calc_sum(arr):
functools.reduce(lambda x, y: x + y, arr[1:], arr[0])
If we call this with an array of numbers, we get the expected result. However, we can call the function with other types without a crash.
calc_sum([1, 2, 3]) => 6
calc_sum(['a', 'b', 'c']) => 'abc'
calc_sum('abc') => 'abc'
If we get such an input, likely something wrong happened earlier in the stack. If we had a type check, we would find the problem quickly. Without a type check, the problem will pop up somewhere else since we expect the return value to be an integer, but it ends up being a string. Or we might actually have a sequence of events that does not result in a crash at all.
The example is a bit contrived and perhaps doesn't make the strongest argument for runtime type checking, but it at least suggests scenarios where we might detect bugs earlier.