Error Checking with Dynamic Typing

One of the common complaints in our office about Lua is that the use of dynamic typing means that most problems in the code aren’t discovered until run-time.

Since the types of variables isn’t known until you’re actually running the program, you won’t know ahead of time if you called a function with the wrong number of arguments or if you tried to take the square root of a string.

The problem with this argument is that even when using a statically typed language (like C++), there are still all kinds of problems that won’t be discovered until run-time. For instance an off-by-one error in a loop, using an uninitialized variable, or any type of logical error. So while compile time reporting of type errors is helpful, it’s not sufficient.

The way to catch these types of problems at “compile time” is to have a suite of unit and functional tests that exercise all of the code’s features. These tests can be run every time you compile, check-in or make a refactoring to ensure that the code is working properly.

Writing unit tests takes programming time, while static type checking happens automatically. Fortunately, you don’t need to write explicit type checking tests, since the functional tests will do this implicitly.

One Response to “Error Checking with Dynamic Typing”

  1. Marek Sieradzki said:

    Jan 05, 11 at 1:15 pm

    That’s silly argument. C++ is not based on any theory and isn’t the best statically-typed programming language there is. It’s very easy to beat such primitive language. Try comparing it with Haskell/Agda. When writing functional code (you can write imperative one too) once code passes type check it’s correct in 99% cases.

    BTW allowing null by default is source of countless bugs.

    Powerful type system can express what you have to do check in Lua using several unit tests. And when it comes to real unit tests I can write them where really needed. NS2 Scoreboard bug is nice example. :)

    There was a vote on website/conference (I don’t remember): which dynamic language do you like the most? Most people chose F# which in most cases doesn’t require specifying types but is statically typed.


Leave a Reply