我曾经因为在公共场合发表这些观点而受到批评,但现在我要说的是:
动态类型语言中编写良好的代码遵循静态类型约定
在使用过Python、PHP、Perl和其他一些动态类型语言之后,我发现用这些语言编写的良好代码遵循静态类型约定,例如:
Its considered bad style to re-use a variable with different types (for example, its bad style to take a list variable and assign an int, then assign the variable a bool in the same method). Well-written code in dynamically typed languages doesn't mix types.
A type-error in a statically typed language is still a type-error in a dynamically typed language.
Functions are generally designed to operate on a single datatype at a time, so that a function which accepts a parameter of type T can only sensibly be used with objects of type T or subclasses of T.
Functions designed to operator on many different datatypes are written in a way that constrains parameters to a well-defined interface. In general terms, if two objects of types A and B perform a similar function, but aren't subclasses of one another, then they almost certainly implement the same interface.
虽然动态类型语言当然提供了不止一种解决难题的方法,但这些语言中大多数编写良好的惯用代码都密切关注类型,就像用静态类型语言编写的代码一样严格。
动态类型并不会减少程序员需要编写的代码量
When I point out how peculiar it is that so many static-typing conventions cross over into dynamic typing world, I usually add "so why use dynamically typed languages to begin with?".
The immediate response is something along the lines of being able to write more terse, expressive code, because dynamic typing allows programmers to omit type annotations and explicitly defined interfaces. However, I think the most popular statically typed languages, such as C#, Java, and Delphi, are bulky by design, not as a result of their type systems.
我喜欢使用带有真正类型系统的语言,比如OCaml,它不仅是静态类型,而且它的类型推断和结构类型允许程序员省略大多数类型注释和接口定义。
ML语言家族的存在表明,我们可以享受静态类型的好处,同时也享受动态类型语言的简洁。实际上,我使用OCaml的REPL来编写临时的、一次性的脚本,就像其他人使用Perl或Python作为脚本语言一样。