The PL series - In defense of dynamic type systems
Last Update: 2024-06-22
This is the programming language series on this blog. This series of blog articles is trying to explain certain programming language design decisions/paradigms.
This article is about dynamic type systems and why they are a valid paradigm for certain applications.
First of: What is a dynamic type system?
Programming language like ECMAScript or Python famously don't use explicit types, but also shells like (ba)sh or PowerShell.
In dynamic type systems you do not have the specify the type of objects and type checking is performed at runtime (e.g. primitive types). This typically allows you to freely modifiy structures used, like adding properties or functions.
Consequences
The goal of dynamic type systems is to allow the programmer to the create programs without thinking about (your own) types (at least that should be the goal here). But types still have to be checked, if you call functions manipulating lists or strings.
This means that programming languages using a dynamic type system, typically also feature a heavy use of implicit type coercion (implicitly converting types). E.g. in ECMAScript you have ==
, which implicitly converts types and ===
which only checks equality of objects with the same type or "" + 0
is evaluated to just "0"
.
Also, a programmer has to write more tests, because the structure (objects, function signatures) has to be tested as well.
Due to types being unknown before actually running a program here, programming languages using this type system are typically interpreted or have a compiler producing comparably slower programs or target a VM.
Another consequence is that, it is harder to offer code completions because the code editor/LSP has to look into function bodies quite extensively to guess the valid usage of a variable.
Refactorings are also made harder, because you can't just statically type check your whole program for errors, because of the change. The programmer has to creatively employ the use of regex to search and destroy (replace) or waste countless hours using inferior search methods (not counting awk).
Advantages
Dynamic type systems allow a programming language to be, well, more dynamic. This allows you to:
- retroactively fix mistakes in a console interpreter
- sometimes fix the standard library (or break it)
- polyfilling
- not needing to express complex structural behaviour in types (but in documentation).
My opion
I prefer using statically typed languages for larger projects. But for very small programs, application configuration or shell-like senarios, I prefer the dynamic nature of dynamic type systems.
Especially the relatively poor LSP experience and refactoring hell using dynamically typed programming languages make them unsuited for larger systems. As a PHP programmer sometimes handling older PHP code, I know.
Also: When using JSDoc with ECMAScript, you partially don't use a dynamic type system anymore.