Wednesday, October 3, 2007

Static vs. dynamic typing

Several people that I somewhat respect blogged how good dynamic typing is and how restrictive static typing is. I feel uncomfortable about as I see how well static typing could facilitate software development process.

I do not see it as restricting.

I see it as facilitating.

I do not argue with that good programs could be written using dynamically typed languages. A plenty has been already written. And there are quite a lot of awful programs written using statically typed languages.

I also do not argue with that dynamically typed programs are usually simpler to type, since that there is less to type.

However programs exist not just for being executed. There are other tools that need to read the program beyond compiler or interpreter. There are other humans that need to read the program. And the human that will wear your skin will be other human in a year or so if you worth anything as programmer. So when writing programs, you need to address that future you as well.

The type is a specification of the value expected to be. The compiler (or interpreter) checks that these specifications are consistent. It also can optimize basing on these specifications at own leisure.

However other tools are able to use these specifications as well. If we take Eclipse Java IDE, there are following facilities that jump to mind when I think about static typing:
  • Refactoring
  • Navigation to type definition
  • Incremental compilation and error checking as code is typed
APT-based code generation is another example of how static typing information could be used.

And this is possible even with as broken type system as Java's is.

Humans also benefit from type annotations. Type information communicates (albeit incompletely) a contract of the component. The expected kind of value is specified in a standard place and in a standard way. If type annotations are missing, this information would have been communicated anyway, but other means were used (for example, comments).

Most dynamically typed languages that I know support optional type annotations. Some typing information could be inferred basing on source code in dynamically typed languages. However, such inference will be incomplete, and that will limit tools and understandability of the programs. For example, refactoring will not work reliably.

Another issue is that Java requires too much type annotations even in places where such information could be easily derived (for example, collection for and final variables). Generics in Java are hopeless broken as well, but I have already ranted about it.

No comments: