posted: February 29, 2020
tl;dr: Dynamic typing if you dare, static typing if you must...
For those who, like myself, worked in primarily statically-typed languages earlier in our careers (such as C/C++ and Java), dynamic typing seems weird at first. We’re used explicitly declaring variables and telling the compiler exactly what type of value will be stored in each variable. This allows the compiler to reserve the exact amount of memory needed to hold the declared type, and to know exactly where in memory it will be located. Without this information, the compiler can’t compile the program.
Why on earth would you ever want to do this?
With dynamic typing don’t have to invent a new name, but maybe you should anyway. It can be confusing for others reading your program to realize that the type of the variable named name has changed. Another programmer might try to modify your code and not realize what the type of name is at the point where the code is being modified, causing an error. The error may not be caught until runtime.
This simple example is not why dynamic typing is loved by so many. The main benefit of dynamic typing is that it allows code to more easily adhere to Postel’s Law, which arose in the early days of the Internet: “be conservative in what you do, be liberal in what you accept from others”.
When writing a function that is passed an argument, Postel’s law says that your function should work across the widest variety of possible input argument values. Dynamic typing allows the input to be any type, with the binding happening at runtime. If your function just needs the input to have a few properties, attributes, or methods, then it can access just those needed items. As long as they are supplied in the input, the function will work, regardless of what other properties are present or what the type of the supplied argument is. This can be incredibly useful when parsing networking packets, implementing APIs, or writing lower-layer services used by higher-layer application code.
Yet statically typed languages such as C/C++ and Java are still very popular, especially for enterprise-class applications. There’s an argument that, as team size and codebase size grows, enforcing static typing can bring benefits. Forcing programmers to declare all the types that their code accepts provides documentation and clues to other programmers. It allows type mismatches to be caught earlier, at compile time instead of runtime. The type declarations can be used by IDEs to provide hints to programmers as they are entering their code, for catching errors even earlier than compile time.
Previous: The joys of duck typing
Next: Lists and arrays