91 points · by susam · 5y ago · 427 comments
I'm the same with strong static typing. At its most basic, why would I give up getting the computer to automatically check for me at compile time that I'm passing the right number of parameters to a function, that a parameter is an array and not a string, a field can never be null, and that I haven't made a typo in a variable name? Coding without these trivial checks of correctness feels archaic and backwards to me.
To make up for it in a dynamic language, you end up having to reimplement what a type checker would do for you with no guarantee you didn't miss something or make a mistake, with the added cost of e.g. polluting your projects with noisy defensive code that double checks the types of parameters, adding extra tests, and bolting on linting, analysis and IDE tools to help.
I'm with the other posters too about the article content, if you haven't coded in a language like OCaml, Haskell, ML etc. you really don't know enough about what strong static types offer to discount them. Java, C and C++ have much weaker checks of correctness and lack type inference + pattern matching that make strong types pleasant to work with. The article says more about e.g. Java vs Python.
You want strong static types + tests, they're not mutually exclusive at all but complementary.
As you say, with ADT's and null safety, you can be a lot more judicious about testing to get to the same level of confidence.
When working with Rust or Swift, I'm honestly usually getting away with some integration tests, and whichever unit tests came about organically when a particular section was particularly well suited to TDD. But "code coverage" is a much less pressing concern.
Even when using modern stuff correctly on a mature codebase fuzz testing will find bugs. So if you don't fuzz test and someone evil has your binary then they'll fuzz test for you...
See what I did there?
Testing can't really substitute for types. They're two diametrically opposed approaches to impeding bugs.
In a dynamic language you end up writing a number of tests that would be covered by a static type system and writing a number of tests that would not be covered by that. Going from dynamic to static typing is a replacement for some of the former, and none of the latter.
I don't understand this. This makes a lot of sense when you make complex enterprise products depending on unstable 3rd-party libraries but for personal project this just inflates the time you need to get the thing done. I just code exactly what I need and check if it works and can't imagine dedicating time to writing additional layer of code to automate this checking. Even when I code pure functions which are a lot easier to test.
A solid type system helps a lot in making refactoring a less fearsome endeavour, but a reasonable test coverage on top of static checking makes it even more so.
Also, automatic perf tests that keep track of regressions and improvements are just awesome.
Tests have advantages, but they also hinder your agility by increasing the costs of the initial version and of making major changes.
Hard to update? Good tests! Well understood problem sphere and product? Good tests! High cost of failure? Good tests! MVP with no actual current users? No TDD. Exploring the product space and update cost is low? No TDD.
I hate tests with a passion, but sometimes I'll write hundreds even for a tiny personal project - when that tiny personal project is going to be at the core of another thing and I want to make absolutely sure that it is working correctly in every way.
Like that time I wrote a process manager for node.js applications because I realized PM2 is a buggy inconsistent mess with race conditions all the way down. Gotta make sure mine works better than that...
def ok(a, b): assert a == b, (a, b)
from .util import ok
ok(Parse(b'.25').do(0, real), (3, ('real', 0.25)))
ok(Parse(b'1.5').do(0, real), (3, ('real', 1.5)))
ok(Parse(b'-1.5').do(0, real), (4, ('real', -1.5)))
ok(Parse(b'+1.5').do(0, real), (4, ('real', +1.5)))
If this results in an exception at import time, I sometimes have to comment out one or more of these tests while I fix parts of the bug.I mean, I do do some manual testing. Sometimes it's easier to bang on a function and decide whether the output looks right than to figure out what the results should be from first principles. But it doesn't take very many repetitions of a manual test of something like the above before it's the manual testing inflating the time needed, not adding another ok() line.
This is especially true for debugging. Adding automated tests is often a faster way to debug than to add print statements or to step through things in a debugger. Sometimes I take the tests out afterwards, but more commonly I leave them in. And with things like Hypothesis and QuickCheck, tests can have a much higher strength-to-weight ratio than simple tests like the above.
It's also a breath of fresh air when I'm trying to understand what some code is supposed to do, or how to call it, and I come across a one-line test like the above.
Speaking of how to call things, sometimes I do test-driven development so that my internal APIs don't suck. And sometimes I don't and wish I had. There are a couple of lines of code in the same project that say this:
array = Thunk(lambda: drop_ws(b'[') + Any(pdf_obj) + drop_ws(b']'))
array.xform = lambda d: ('array', d[0][1])
And, you know, that's just shitty, shitty code, because that was a shitty way to design that interface. And maybe if I'd written that code test-first, instead of just charging ahead madly implementing the first thing that came to mind, I would have realized that when I was writing the test, before writing the implementation. Now, if I want the interface to suck less, I have 700 lines of crap to refactor to the new interface, which probably means either throwing it away and starting from scratch, or incrementally refactoring it while maintaining both interfaces for a day or two. And that's inflating the time I need to get the thing done.It would have been less work to fix it at design time, the way my friend Aaron taught me: first, write some application code as if the ideal library existed to write it with; then, write the library code that makes it run. And that's just so much easier when that application code is just a unit test.
However, as with most things, I disagree with Robert Martin's point of view on this. I can easily conceive of writing software without TDD, or even without tests. In fact, I do it frequently. Tests are often valuable, and TDD is sometimes valuable, even in weekend personal projects. But they aren't always worth the cost.
This is entirely dependent on the type of application that you're dealing with.
A web application backed by a database, especially CRUD style, acts as little more than a pass through layer. You're getting everything as a string from the browser, storing it in the database with a SQL string, usually transformed by an ORM layer. In that style of application, the types are maintained in the database itself.
Having a language with strong static typing in that middle layer between the browser and the database only serves to add a huge amount of headaches and extra friction, especially when you're not even using each variable that comes through on its way to the database.
The only thing you're doing in that situation is adding an extra set of type checks that you have to keep in sync between the database and the application layer for virtually no benefit.
In your example, the database and the application layer must be kept in sync regardless of whether you use static typing or not. The benefit of static typing is that it can be enforced before you push to production or write a test for congruency.
This is handled automatically by a large number of ORM tools in dynamic languages (Ruby, PHP, etc). It's a non-issue.
I've spent significantly more time in my career debugging issues in statically typed languages used as an app server in front of a database than I have in dynamically typed languages.
You're doing some processing work in the language? Calculations, ML, etc? Static typing is the obvious way to go.
If you're just sticking things in a database you're going to end up wasting a lot of people's time (and subsequently, the money that goes to pay them). In 20 years, I've never seen it be a good choice but I've seen a lot of people married to the delusion that it is while other people are getting real work done.
This may be one of the differences of requirements that causes disagreement here. I can see how this might work if your app:
* Loads data from the client
* Later displays that data, unchanged, to the client
In that case, treating everything as a string is great, because you never need to use it as anything else.
In my case, I've never actually worked on an app that didn't need to do more than just display the data at some point. In those cases, I don't want to get everything as a string from the browser. My data is often not merely a string, and treating it as such means I have to deal with stupid questions like whether "0" == 0 == "null".
In my work, I have spent many, many hours repairing issues that could have been avoided if the client and server were both statically typed (and on the flip side, in services that are statically typed, rarely run into those same problems). I'm sure that this can be remedied by just "doing it better", but I'd rather operate from a foundation where doing it right is easier than doing it wrong.
Instead of strings, I want my apps to have a statically typed contract between the client and the server that specifies what endpoints are available and the data structures they accept and return. Ideally this is in a shared class/type definition file, but two definitions kept in sync can work as well if they don't share a language.
The common argument against statically typing your network requests at each end is that you're not resilient against unexpected values and/or version differences, but:
a) It's trivial to tell any JSON parser to ignore unknown values, so adding new optional fields to the request is never a problem.
b) If your app ever uses the data received from the client, version differences will eventually break your dynamic code, too. You'll just only be told so at runtime, potentially only after loading the bad data from the db.
If you ever use your app's data for anything other than rendering a template, you have to make breaking changes to your data structures very carefully, and using a strong layer of static types on both client and server helps to ensure that you consider all the breaking changes and either avoid them altogether or somehow mitigate them.
I agree that this is a different scenario. If you're able to have the client control the input to ensure only the correct types are passed in there may be some additional value there to keep things more sane.
However, how much of the data that you're dealing with in the client on the server and in the database are you really working with in the server itself? 1% of the variables? 2%?
Generally any heavy work will be handled in either the database itself or a background job just to reduce wait time for the client.
And if that's the case, you're spending the time defining types for the client, server and database, keeping them in sync, having to change them in each place and creating this exercise for the other 98-99% of variables passed in and out of your server just to gain the static benefit for the 1-2% where you're actually working with it in the server on the web request.
It's significantly more work with questionable benefits IMO.
Same argument could be made the other way, if you haven't used Smalltalk, Clojure (and other languages that are strongly dynamic), you shouldn't discount them.
Clojure has some cases where it's insane how elegant you can make the solution, but frankly static languages with good type systems and tooling come close enough but don't have the scaling downsides.
Yeah, agree. But this is hardly surprising. Learn enough about ANY language on this planet and you'll come to the same conclusion.
The beauty of Clojure is that it mostly provides you with tooling and other facilities that leads to elegant and more importantly simple code.
I'm, not sure if Smalltalk and Clojure do this better, but since I've gotten into static languages, I basically haven't looked back, and I haven't missed the dynamism much at all.
Yes, languages that are truly dynamic (ships with a REPL, has a instant change->run this snippet workflow, can redefine anything in the runtime AT runtime) does work a lot better than Python which is basically comparing the type systems of Java and Haskell.
Give it a try. Worst that can happen is that you now have tried and learned something different, I'm sure it'll give you some knowledge that'll be helpful in any programming language :)
Que?
Python 3.9.0 (default, Oct 10 2020, 11:40:52)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+"1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +:
'int' and 'str'
While a weakly typed dynamic language like JS will allow for it Welcome to Node.js v16.0.0.
Type ".help" for more information.
> 1 + "1"
'11' class A(random.choice([B, C]):
...Writing correct, maintainable software is hard. You need both tests and typechecking.
Java can put you off with all the boiler plate. That's not a requirement of static typing.
F# skirts-around some of the limitations with just-in-time design-time type generation ( https://docs.microsoft.com/en-us/dotnet/fsharp/tutorials/typ... ) though Microsoft pitches it as a "better T4" for F# specifically, I think it's far more powerful.
The way things are looking, C# is set up get some form of higher-kinded-types in the next 3-5 years (hurrah!) - but from what Mads and the design-team have said it seems like they'll be implemented without significant changes to the CLR's type-system - so be prepared for everything to be implemented as glorified structs (and don't expect struct inheritance either...) with excessive amounts of implicit-conversion.
The feature you state (F# unions) - that simplification has some positives as well. I can exhaustive pattern match for example. I can always use composition/pattern matching/active patterns to mix in other assemblies types cases. Is it really limiting that it doesn't do this? Would changing this mean more complexity and make other language features harder to deliver? All features introduce some additional complexity, and it more than linear typically. F# also has some interesting patterns that were either introduced first there en masse (e.g Async) or are easier to use there.
I'm a fan of static checking, and conciseness with performance close to the platform it is hosted on and is easy to reason about. I'm also a fan of easy to read and clean code that isn't "scary" to look at. F# seems to strike that balance well compared to other JIT functional languages, at least from where I’m sitting. Too much complexity and you start scaring people away and/or too much abstraction in the codebase starts to occur trading off maintainability.
I don't understand. All languages, without exception, must compile down to a "worthless untyped jargon". Only assembly can execute.
Javascript is a garbage layer of broken standards, a worst of breed language that shouldn't have to exist between a strict typed higher level language and lower level bytecode, but everything on the web now needs to be built on top of it, compile to it first, and run through one of a few JS engines. You can never build a full fledged language on top of something that has to go through JS... so TS, coffescript, et al are always going to be pseudo typed but not truly solid or permanent solutions.
Ultimately I think ECMA standards will finally move toward strict types in JS, and in a decade more we'll have something that for all intents and purposes is exactly what Flash was in 2009.
TypeScript, by design, does not produce nor introduce any "noisy defensive code": the point of TypeScript was that type-safety in JavaScript can be achieved without any runtime cost.
The only significant code-gen that TypeScript does do by itself is stuff relating to ECMAScript modules (e.g. wrapping and repackaging your TypeScript module for other module systems).
...with the exception of when you take a modern TypeScript compiler and specifically instruct it to target ES3 (lol) or perhaps some older variants of ES5 - at which point the code `tsc` generates is still so minimal you'll still need to bring-your-own polyfill/monkeypatch libraries. This is stuff like reimplementing the spread-operator or `for(of)`, and so on.
the web runs on JavaScript because it's extremely forgiving and therefore stable. there can be lots of errors and things keep chugging along.
A common misconception.
In tests, you test that values are correct, the types take care of themselves.
Types being correct does not imply values being correct, so you will have to write those tests anyhow, although you maybe be fooled by the safyness of static typing[1] that you don't have to.
Values being correct does imply that the types are correct, so if your tests pass, then your types are also obviously correct. (If a==3 then I don't have to check if a is of type pink elephant, it obviously isn't).
So that's the in-principle argument. And it turns out that this is completely supported in practice as well: neither the defensive code nor the extra type-based tests that you propose must be the result actually occur in dynamic code-bases with any frequency.
That said, static types certainly have their uses, particularly in being machine-checked documentation and also for producing faster code without going through crazy amounts of extra effort.
[1] https://blog.metaobject.com/2014/06/the-safyness-of-static-t...
> In tests, you test that values are correct, the types take care of themselves.
How can you be sure your function e.g. returns an integer for all values and never undefined for some values? Unit tests cannot check this exhaustively unlike type checkers.
> Types being correct does not imply values being correct, so you will have to write those tests anyhow, although you maybe be fooled by the safyness of static typing[1] that you don't have to.
As I said, types compliment tests, they don't replace them but types do reduce some of the burden on writing tests for you.
To nitpick: type checking can prove values are correct when the type system is powerful enough (i.e. dependent types) but this isn't practical enough for mainstream yet.
Right, which is actually an argument against the claim that you have to write more tests with dynamic typing.
Urgh, that reference is such a shallow, straw-man facade of static typing. This is especially evident with its link to https://www.sans.org/top25-software-errors/ and claim that those "don't look like type errors to me", a list which includes:
- 16 even says 'type' in the title: "Unrestricted Upload of File with Dangerous Type"! Phrased as a type error, this would be "savePicture: Required argument of type 'Either[PNG, JPEG]', given 'Array[Byte]' instead"
- 2, 3, 6, 11, 18 are all injection attacks, which are classic type errors (AKA "stringly typed programming"). Phrased as a type error, these would be "+: Cannot append 'Foo' with 'FormInput'", where 'Foo' might be 'SQL', 'ShellCommand', etc.
- NULL pointer dereference is Tony Hoare's 'billion dollar mistake', which as type error would be "Expected 'Foo', given 'null'"
- integer over/underflow, buffer over/underflow, out-of-bounds access, etc. can all be mitigated with types like 'Maybe', 'Try', etc. at the cost of a bounds/flag check. If we don't want runtime checks, we can instead track memory usage bounds in the types, and have the compiler check that we're allocating enough.
So many of these problems are avoidable with types, even before we go into fancy stuff like dependent types, linear types, etc. In particular, most of the burden to getting this right is on languages and libraries, not application developers.
For example, if a database library can only be queried by an 'SQL' type, and the only way to construct that type is via literals and a 'withParam[T]: SQL -> T -> SQL' function, then application developers are unable to introduce injection attacks; the library forces them to do the right thing. Instead we get 'dbQuery: String -> ...', 'runShell: String -> ...', 'response.withBody: String -> ...', etc. and draw the conclusion that types can't help :(
The SQL case is much more complex. SQL is such a non-standardized language in practice, and such a complex one, that trying to offer a generic SQL library that presents an AST as the API for even the most popular RDBMSs quickly gets complex. So, you end up with convenient string->SQL converters, and then people stick untrusted input in those strings. Not to mention, your fancy AST library still needs to spit out SQL text to talk to most DBs, so you end up needing to sanitize identifiers in your own SQL->string conversion.
So what you do? I find code that uses excessive type checks too verbose, you end up doing things only to make the compiler happy, even if you know that a particular condition will never happen (e.g. a variable that can be null but given a particular condition you know that it cannot be because it was initialized earlier, but the compiler is not smart enough to know).
So to me using static types makes sense where types are used by the compiler to produce faster code (embedded contexts, basically, of course I don't use Python on a microcontroller) and as a linting of the code (Python type annotations or Typescript).
You are confusing "type" with "static type". This is user input. You are not going to statically typecheck your users.
(See other comment for stringly-typing).
If I generate values within a function that are arguments to a constructor call, and the make the constructor call and return the result with no further manipulation, I can—without exhaustive, or even any—testing be quite confident that the function will return the type for which the constructor so called is the constructor any time it returns, and fail otherwise.
In those cases, the difference between a compile-time check and a run-time check is much smaller.
I also find 'phantom types' incredibly useful. For example, we might have a database or key/value store, where the keys are represented as strings and the values can be strings, integers, floats, booleans, etc. We can 'label' each key with a "phantom type" corresponding to the values. This way, the compiler knows exactly what types are expected, we only have to handle the expected type, we don't need any boilerplate to wrap/unwrap the database results, etc.:
-- Haskell syntax
data DBKey t = DBKey String
dbLookup :: DBKey t -> Maybe t
dbLookup (DBKey key) = ...
name = DBKey @String "name"
age = DBKey @Int "age"
// Scala syntax
final case class DBKey[T](override val toString: String)
def dbLookup[T](key: DBKey[T]): Try[T] = ...
val name = DBKey[String]("name")
val age = DBKey[Int ]("age" )
These are called "phantom types" since they don't actually affect anything about how the code runs; in particular, the definition of 'DBKey' requires a type ('t' or 'T') but doesn't actually use it for anything (it just stores a String). We could get rid of these 'labels' and the code would run identically; or we could have the compiler infer all these labels (defaulting to some uninformative type like 'unit' if it's ambiguous). However, the fact that we've explicitly labelled 'name' with String, and 'age' with Int, constrains the rest of our code to treat them as such, otherwise we'll get a compiler error. For example, if we try to look up a name then our result handler must accept a String, and nothing else; if we provide a default age it must be an Int; etc.Of course, we can combine such 'labels' with more meaningful types; so that 'name' looks up a 'Username'; 'age' looks up an 'Age', or a 'Nat', or a 'Duration'; or whatever's convenient. It can also be combined with other type system features like implicits/ad-hoc-/subtype-polymorphism, e.g. to decode JSON as its read from the DB, etc.
I've used the example above in real Scala applications when accessing a key/value store. I've also used phantom types (again in Scala) to help me manipulate Array[Byte] values: in that case the bytes could either be 'Plaintext' or 'Encrypted', they could represent either a 'Payload' or a 'Key', and each 'Key' could be intended for either 'Encryption' or 'Signing'. Under the hood these were all just arrays of bytes, and the runtime would treat them as such (using Scala's 'AnyVal' to avoid actually wrapping values up), but these stronger types made things much clearer and safer.
For example, we can decrypt and verify a message which carries its own 'data keys' (encrypted with a 'master key'):
def decrypt[T](
key : Bytes[Plaintext, Key[Encryption]],
data: Bytes[Encrypted, T],
): Try[Bytes[Plaintext, T]] = ...
def validated[T](
key : Bytes[Plaintext, Key[Signing]],
data: Bytes[Plaintext, T],
): Try[Bytes[Plaintext, T]] = ...
def decryptMessage[T](
master : Bytes[Plaintext, Key[Encryption]],
dataEnc: Bytes[Encrypted, Key[Encryption]],
dataSig: Bytes[Encrypted, Key[Signing ]],
message: Bytes[Encrypted, T ],
): Try[Bytes[Plaintext, T]] = for {
encKey <- decrypt(master, dataEnc)
sigKey <- decrypt(master, dataSig)
raw <- decrypt(encKey, message)
valid <- validated(sigKey, raw)
} yield valid
The compiler makes sure we never try to use an encrypted key, we never try to decrypt plaintext, we can't decrypt with a signing key or a payload, we can't validate signatures with an encryption key or a payload, our result type must match the message type, etc. After checking, these types are "erased" to give an implementation of type '(Array[Byte], Array[Byte], Array[Byte], Array[Byte]) => Array[Byte]', which we could have written directly, but I certainly wouldn't trust myself to do so!It is confusing that people talk about C in terms of being a typed language. The types are an annotation so the compiler knows how much memory to allocate / read. All the side benefits of having to spell that out are incidental.
That sort of typing is a distraction. A programmer does not care that they are passing 4 bytes as the first argument. That isn't really trying to squeeze anything useful out of a type system. They care that they are passing something recognised as an ID, not that it has 4 bytes.
Using C/C++ as an example of a typed language doesn't say much. The guarantees are more a culture of how to use the language than in the language itself.
struct ID { uint32_t val; };
void check_id(struct ID id);I never understood this, how is it possible that a developer calling a function doesn't test if they are calling it right. Once they test it, how does the additional compiler test matter?
Unless of course your calling function is mutating the value of a variable across so many types that it's impossible to realistically test it. It would then make sense to use a type to prevent the variable from being something it shouldn't.
But most people, don't have that situation most of the time. Even in a big application.
May be that explains why something like Python has such wide adoption.
Of the all the constraints I've faced while developing software, reusing variables for many purposes in one code block isn't one of them.
Maybe I am just more absent minded than most dynamic programmers, but live IDE diagnostics and autocomplete are very important for me.
And if you have, you probably know that its awesome but for most purposes doesn’t compensate for the weak ecosystems of the languages that have it, compared either to poorer (higher cost to satisfy for lower benefits) statically typed languages or dynamically typed languages with or without available optional static type checking.
Less opinionated/experienced with strong type systems though, I do appreciate the flexibility of being able to hack things together to see if they work - then improving upon the solution. strong types seem to make that harder.
I often build systems, then break them up to take the working parts out, then put a subset back together.
The type system is like magnetic Lego that lets you snap pieces together.
With a dynamic system it is really difficult to break things apart and then put them back together (without ever running the code, and with 100% accuracy and immediate feedback).
Dynamic languages can be very productive for small teams.
I definitely liked the productivity of F#, but the ecosystem was lacking. Often in dynamic languages the ecosystem more than makes up for the lack of compile time checks.
Those are all functional languages, so this argument seems to be the "functional is better than OO" argument, typing is not the primary factor (but of course to the degree that FP allows static typing to be more intuitive, that's a plus). What examples of static typing with OO or procedural languages that are only a "pleasure to work with" can we look at ?
I've never been able to make heads or tails of Girard's paper but http://pauillac.inria.fr/~fpottier/slides/fpottier-2007-05-l... is an introductory divulgation of some of the pre-Rust history of this stuff. It makes me think I should read Wadler's 01990 paper.
So I think functional languages kind of had a head start, but also in a sense they have an easier problem to solve. ML's type system doesn't even have subtyping, much less mutation and resource leak safety.
OCaml and Rust would fit the bill. You can do procedural and OO in both. You could add Scala to that. I think the conclusion is not that "functional is better than OO" but "they both have their strength and are not mutually exclusive".
To give an example from Haskell:
You can stick everything into IO, or you can be more careful with your effects.
Or to give a more main stream example:
Even in a language like Go, you can do lots of runtime casting (which is essentially dynamic typing), or you can try to cajole the type system into recognizing what your are doing statically. You can do the latter effort incrementally.
What I found problematic is that system and integration tests is generally relegated to be done outside of the programming process. It is instead the administrators job to write an extensive test system to verify that the program actually do the job that it was written for. You start to wish for a very different set of tool design when the programmer and administrator is the same person.
What about the decision whether a function argument is an integer or a string? A floating-point value or an optional floating-point value? How could the compiler ever decide that?
The size of an integer is only a very, very small part of a modern static type system.
If a number is an int, float, large or what have you, the question I would ask is how many decimal points should be printed or if you divide 2 with 2, do you get 1 or 0.99999. A good language/compile should have sane defaults that works almost every time, while giving me options to override it if in testing it get an unexpected result where a human would disagree with the computer.
The source of tests should be the customer requirements, and types is just an set of automatic tests being applied on the code which has no direct connection to the customer requirements.
Its type system was so lame that it gave rise to most of the "Gang of Four" patterns, most of which are just workarounds for Java- not some first order principles of programming.
So you had these awkward and verbose "patterns" and polymorphism and naming a bazillion new types that were almost the same as each other, and STILL had runtime type errors and crashes. What's the point?
It's no wonder at all that every desktop app I installed on my Linux machine in 2008 was written in Python.
It's no wonder someone thought it was actually a good idea to run *JavaScript*, of all things, on the backend *and* the desktop. Holy crap- how bad do statically-typed languages have to be to make people want JavaScript?! (I'll tell you: they have to be Java and C++98 bad- that's how bad.)
Thank goodness for Swift, Rust, Go, etc in the post-2010 world.
For the last few years people are looking down their noses at dynamically typed languages, but I think statically-typed languages almost died thanks to Java and C++.
Java wasn't released until after the first edition of Gang of Four. C++ is probably what you should be pointing the finger at.
Those two are just minor syntactic sugar. They literally make miniscule difference practically.
I think you forgot C++11 :-)
And that space is where your data itself is highly dynamic. When you just want to represent data as maps, do generic operations on maps, then spit out more maps back to something else. This description applies to many many real world systems, particular in the more business-type domains.
Another space where dynamic really shines is dealing with relational data in a relational way. Relations are just sets of maps, the most natural thing in the world to work with dynamically. In a dynamic language I can just write code that peaks into the map, transforms certain fields, then passes the whole thing on down the line. I don't care what combination of selects and joins got me that relation, and in reality there will be many, I want to reuse my functions regardless. Although this is where more structural type systems can help ease the pain over nominal type systems.
I feel like this is a great blog post talking about the downsides of static typing in a real world system: https://lispcast.com/user-wizard-scenario/. I appreciate that the author has real world experience with both Haskell and Clojure and comes from that perspective.
Ultimately I'd say that if a program can be written in a static language, it should be, however some programs deal with information that just defies fitting into your type system without herculean efforts. Just like static languages will look down on dynamic languages for reimplementing poor ad-hoc type checking, dynamic languages can also look down on static languages for poorly reimpelmenting dynamic behavior with a bunch of functions mapping Any to Any.
If I may ask, what ideas are static languages incorporating from dynamic languages? Could you help clarify?
Also, over the past 20 years what you've seen is big advances in the 'semi-static' world like the JVM, where it runs statically typed languages but they have the ability to eval code, redefine their own code on the fly, reflect themselves, they're garbage collected etc. This is kind of a middle ground. It's worth remembering that when Python and Ruby were new, there weren't really any great options if you wanted lightweight syntax with garbage collection. Nowadays there is Kotlin and you can write code that looks very similar to say Ruby, but which often has the performance of entirely statically typed languages.
Lisps and MLs offered this before Ruby and Python got popular. Unless you don't consider them great options?
Something that quacks like an iterable cannot be used as an iterable, unless the trait is explicitly stated — unlike python, where it simply has to quack.
[1] https://channel9.msdn.com/posts/MDCC-TechTalk-Classes-Jim-bu...
> I also realized that the flexibility of dynamically typed langauges makes writing code significantly easier. Modules are easier to write, and easier to change. There are no build time issues at all. Life in a dynamically typed world is fundamentally simpler.
Isn't he mixing static and compiled languages here? I'm also not convinced at all that dynamically typed code is easier to change. Easier to write maybe, but I thought his whole thing was that writing is the easy part and after that software rots and you have to change it.
Edit:
> I thought an experiment was in order. So I tried writing some applications in Python, and then Ruby (well known dynamically typed languages). I was not entirely surprised when I found that type issues simply never arose.
I don't think understanding code you just wrote and not having issues in it is a great experiment with a lot of meaning.
Yeah this is something I take huge issue with. There's always a tradeoff: less comptime issues means more runtime issues.
Comptime issues are predictable and deterministic. Runtime issues may depend on inputs, or external factors like memory constraints, so they're way harder to identify and solve.
Static types are like eating your vegetables. You might get more instant gratification from eating cakes, but it's going to come back to bite you later.
But my sense is that we're gradually swinging back around to static typing via gradual typing + mainstreaming of ML style features like generics, unions, records that are more expressive than the C/Java model.
In part, I think the move to mainstream more ML features is to finally try and address this.
Meanwhile Julia gives dynamic languages some of the same feel as static ones.
Both dynamic and static languages have benefits, so I don’t find it weird that they borrow from each other.
Personally I prefer opting in to use static type checking over opting out.
The error messages are not as nice as if the types were specified at the top level, but there's usually still enough static type checking to know whether the code will run or not before it runs, which is one of the big benefits of static type checking. The other benefit of static types is performance due to compile time optimisations, which Julia can benefit from if the functions are type-stable.
In Python, you can, if you work at it, find a variable in some other process by name, and store into it from another thread. While this is unlikely, you cannot definitively tell at compile time it won't happen. This prevents most compiler optimizations.
Yes, you can do awful things involving creating an optimized loop, detecting at run time that someone broke it from the outside, and switching from compiled to interpreted mode. I think PyPy does stuff like that. It's a huge effort in the compiler and in the runtime to handle such cases.
It's also part of why Python sucks at threading, with the Global Interpreter Lock. There's not enough separation between threads.
The advantages of a dynamic type system are two-fold:
1. Dynamic typing and a meta-object protocol allow for certain design patterns. Arguably makes it a bit easier to write DSL's.
2. You don't have to spend 500 milliseconds typing the word `string` or `int`.
However, in reality:
1. Virtually no one in these threads are actually writing DSL's, or applying any of those design patterns. They're writing line-of-business CRUD apps, and simply don't feel like reading or typing `string` or `int`.
2. Most static languages are getting more sophisticated with type inference, such that you don't have to type `string` or `int` nearly as often (although we can debate whether this actually makes your code more readable or less).
So in sum, most people aren't even getting much if any purported advantage, and in exchange they are giving up a slew of compile-time checks that must instead be manually implemented in (unreliable) tests.
It's just madness. You don't want to type `string` or `int`. It really is as simple as that.
I prefer to write "string" or "int", but it can be borderline impossible to write the type of a complex query, the kind of thing returned by LINQ or the like.
What's the type of a class or struct that has fifty non-optional (not null) fields of various types? Easy! It's just the name of the class or struct.
What's the name of the same class after applying the "select" or "project" operator, with one of the fifty or so fields removed? Umm...
Okay, next: How about the name of the type that is a projection that removes one arbitrary column based on a dynamic, runtime input? Can your static language express this at all?
This is the most basic query operation possible, affecting one column or field, and your fancy static typing has fallen flat on its face.
This is not about typing speed. It's about solving trivial problems with fit-for-purpose tools instead of fighting the compiler.
This is why SQL is still a thing, and why a lot of people massage data with Python or R instead of C++.
Instead of developing normally, writing code, then compiling, then testing, then raising a CR, you work with a REPL that helps you fill out parts of the code as you go. So what you can do is just type
`> :t what_is_this_type?`
where what_is_this_type is a hole for the thing you don't know how to type yet. So with this REPL based development you don't even have to try to figure out the type.
So IMHO, it fundamentally comes down to the power of the statically typed language. If you're working with Java, C++, C#, etc, type inference can help a lot but ultimately can't give you everything you want. Precisely because of that dynamic, runtime input. But if you have a functional language, like Haskell, Idris, or Clojure, you actually can precisely type that input and have something reasonable looking come out at the other end.
I like to use the select/project operator as an example precisely because it is so basic, yet so revealing of the gaps in modern programming languages (static typed or dynamic).
It really is very fundamental to not just verification of correctness, but also performance, data security, API surface design, and a whole host of things that are causing a lot of grief for a lot of programmers. The "ORM impedance mismatch" is in no small part caused by this issue.
Imagine a not-so-hypothetical scenario of wanting to make a Web API for something like "get cloud virtual machine". A virtual machine might have hundreds of properties! Everything from creation time, licensing mode, SKU, status, etc, etc...
So of course, for efficiency, you want the API to only return the relevant columns, right? Currently, there is no way to do this in most programming languages without reams and reams of dynamic typing of some sort, somewhere. One way or another you will be explicitly treating the returned rows as hashtables, arrays of "object", or something. More than likely, you'll have to dynamically generate the SQL/NoSQL query as text. You'll have to write nested loops to handle the rows and columns. Then all of this will have to be repeated on the client side, but likely with different languages. There's a decent chance that the trivial operation of "select {set of columns} from table" will end up executing a hundred megabytes of code in the end-to-end path and take multiple seconds to return a couple of kilobytes of data.
It's madness.
With duck typing you just stuff the data in there and pick it out again.
I did not get it either until I had a couple of years of Python experience under my belt. And yes, you can do that in something like Java too, I'm sure. It's just not as convenient, and the culture will not tolerate it. And yes, there are downsides. (But there a downsides to the spec'ing too, one of them being proliferation of concepts, increasing the mental load of understanding the system.)
I've never seen a Python codebase larger than 10,000 lines, that didn't require exhaustive archeology for newcomers to figure out the contracts. I'm sure that the original authors (who are always long gone) had fun, though.
Correct! I don't want to type it and, more importantly, I don't want to force others reviewing my code to have to read it. One of the very few empirically demonstrated facts about software engineering is that the number of defects is proportional to size of code, usually measured as the number of lines of code. Source: https://softwareengineering.stackexchange.com/questions/1856...
There's a lot of bullshit in software engineering, cargo cults, buzz words, bla bla oriented programming, etc. All with zero empirical evidence. But that the number of bugs per line of code remain roughly the same independent of language has actually been demonstrated.
Thus, I pick Python over more verbose statically typed languages.
I think you're taking that too literally. It doesn't make sense applied to types.
If you have the same piece of code, having types doesn't increase the complexity in any way. Its just more information shown and more validation.
By that logic we should all use the shortest variable/function names possible so that we can minimize the length/lines of code
> By that logic we should all use the shortest variable/function names possible so that we can minimize the length/lines of code
Perhaps we should since there is no research to suggest that short names negatively affect software quality.
To then turn around, and claim that type declarations inappropriately inflate the line count, is absurd.
Having it written there makes code review easier instead of harder. Because you see information instantly instead of having to guess it.
Snorted out loud at that one.
This post seems to assign value to static typing: That it aids in avoiding bugs. It then makes the case that TDD will do a much better job at it, and thus, obsoletes the need for this (having 2 systems would be redundant!).
The problem is, that's just one of the many things static typing does.
static typing also deals with the general problem of discoverability: When I'm writing code, how do I know which features and functions are available, right now?
"Just read a ton of docs and be a walking dictionary of API calls" is a really bad answer to the question. So is: "Welp, re-read the intro page of the docs over and over".
A much better answer would be: Well, at the touch of a single keyboard shortcut, or even 'as you type', you get a curated list of the most likely things you'd want to do right now so you can just eyeball that as you program.
static typing makes that way, way easier to do vs. dynamic.
But, I think even as far back as 2003, Bob "TDD!" Martin was already reframing all coding issues in terms of TDD so this isn't exactly surprising.
1. The type system is not the only consideration, nor is it the most important one for most cases.
2. Language choice often boils down to cultural things: what is already written, who can write it already, the lowest common denominator. This is not always a good thing, but often it is necessary.
3. The tools we use shape the way we think.
4. Tools should be invisible, like an extension of ourselves.
5. Static vs. Dynamic is a false dichotomy. There is a gradualism to it and it includes more than typing.
6. Constraints are important, because they facilitate engineering, confidence and systems thinking.
7. Interactivity is powerful, because it facilitates understanding, expression and domain thinking.
8. There are cases where either of these things are more beneficial.
9. Some languages are half-assing either of those to be more familiar.
10. We should give ourselves more credit to be able to use the right tool for the job.
My suggested answers: 1. We now know, 20 years later, that dynamic-typing languages have not replaced static-typing languages. All of the languages from that '03 blog post are still heavily used. If we look at more recently introduced languages, some are statically typed and some are dynamically typed. Evidently programmers still see value in both of those ideas, and neither looks like it's replacing the other. 2. We now know that it's possible to add type deduction to statically typed languages and type annotation to dynamically typed languages, even older languages like C++ and Java and Python.
Abstractions are very powerful, but when many people work on a codebase, keeping extra checks via static typing imo is good. Unless your Dev team is _highly_ experienced, then you can put away with the training wheels
https://danluu.com/empirical-pl/
The evidence behind strong claims about static vs. dynamic languages - https://news.ycombinator.com/item?id=16287083 - Feb 2018 (1 comment)
The Empirical Evidence That Types Affect Productivity and Correctness - https://news.ycombinator.com/item?id=8618887 - Nov 2014 (17 comments)
The empirical evidence that types affect productivity and correctness - https://news.ycombinator.com/item?id=8594769 - Nov 2014 (9 comments)
Nah, they don't have to be done. Most programmers using dynamic languages just don't think about types until they need to be thought. That implies there's more resources/energy available to think about the actual problem, which often has almost nothing to do with types. Then if you're using something like Common Lisp/SBCL, you can define the types afterwards where they are most critical.
Doing all this well in a dynamic language requires more discipline obviously, since you cannot even release software in a stricter static language if it fails to pass the type checking phase. But it is faster, sometimes significantly faster. Sometimes it may even happen that the coder could not have finished the task in a stricter language, which would imply that the the dynamic language was infinitely faster.
And as someone else said, static types aren't training wheels. You don't stop using them when you think you're sufficiently skilled.
No, dynamic and static languages are going to merge, coming at optional, selective static typing via opt-in static typecheckers on the dynamic side and opt-outs via dynamic escape hatches and/or use of broad (e.g., Any) types from the static side.
My experience with dynamic language rot is that a single developer or a small team can create a clean bug-free dynamic application but as soon as you start adding features, refactoring, or adding developers you get all kinds of runtime-only bugs that creep in. Older unsafe static languages like C and C++ have the same problem to a lesser degree in that the compiler will catch egregious type bugs but things like memory errors, type conversion gotchas, etc. will creep in over time unless you have some really diligent testing and auditing in place.
Dynamic languages are suitable for prototyping, glue, and throwaway code, which is why we used to call them scripting languages.
I do have to add though that today's best static languages like Go and Rust are vastly superior to 1990s-2000s era C or the carpal tunnel inducing "enterprise" nightmare that Java became. Even C++ has improved if you use more modern constructions like lambdas, and nearly all languages have better libraries and better ecosystems than they did back then.
This point is mostly relevant for mathematics. When you define a variable in a program the reader can easily infer the type by the value it was initialised with. Sure, if you just see "10" you don't know if it's a byte or a long int, but that doesn't matter because only the compiler needs to infer those details. For reading the code it's enough to know it's an integer. I agree about complex types, though. In Python and pure JS it gets really complicated when you have to find out about a dictionary's/object's fields by looking at code inserting them one by one.
This breaks exactly when you're dealing with more than one function. Then you have to guess the types of the whole chain of functions.
And maybe that function is used in multiple places, now you need to guess the types of all the places where this function is used.
Considering the use of features like auto, I personally prefer writing unspecified variables while programming and getting the statically inferred types live from the IDE, which for example aids when composing a complicated expression whose type I don't fully know while writing.
If that’s how you feel about auto, wait until you see something like rust’s post-facto type inference.
Clojure programs have a pulse a spark of life that I can mold at runtime with a bit of static analysis via clj-kondo it's a crazy productive creation environment
I am not entirely convinced of the validity of the latter argument.
But a powerful structural type system built on a flexible object model is really a great mix - type as much as you need, ignore types when they get in the way.
[1]: https://blog.cleancoder.com/uncle-bob/2019/08/22/WhyClojure....
> It is just simpler, and easier, and less occluding to write expressive code in Clojure. It requires fewer lines. It require fewer characters. It require fewer hours. It requires fewer mental gymnastics.
This paragraph is not only about "faster to write". It's about faster to understand, easier to maintain (less code to understand), easier to change and a lot more. I urge you to re-read the post again and think about what's being written,
> I think it's time to stop following what he things.
I think this is true for many "leaders" in programming. We should never follow people because they are (self-described/community-described) as "thought leaders", it simply leads to too much cargo culting. You see this in Clojure, VueJS and so many other ecosystems.
Ideas are good if they are good ideas, not good because of who said them.
> Ideas are good if they are good ideas, not good because of who said them.
You're right about that, I always insist a bit more with Robert Martin because there is a lot of cargo culting around what he says. Clean code and TDD are other good examples of that.
I have used dynamic languages a lot and I enjoy them in many ways, especially Python. But I've been using Go for a few years now and I'm hooked. For me, Go is pleasant enough that I don't mind its warts and I loooove the compile time checking. It has some other great features, tooling-wise as well.
I still love Python and I will continue to use it for the foreseeable future but I prefer Go when I have the option. If anything, Go has sort of rekindled my appreciation for static typing. I'm kind of hunting for a reason to learn Rust sometime soon.
Runtime is funtime with dynamic languages and I'm kind of burnt out on that. :)
Dynamic langs can be static (but without the guarantee that it always will be), static languages can be dynamic but with difficulties.
If guarantees are the issue, standards, language features/structure and constraints are the crux. Take a dynamic language, and explicitly label what is dynamic, and what is static, and you can restore static guarantees, while still having dynamic features if need be. Hybrid langs, with better reflectivity will win - you can have "both".
That said, software development models that don't trust their devs are always going to choose locked down languages, and claim this is the only "viable" way - much like those companies that claiming they cannot seem to hire employees, but don't mention "at the price we want".
I'm not shipping the tests. The fact that they work is very nice, and it can prove that the code under test is working, not that all attempts to use the code in something larger aren't broken.
So all that's left in this article is that dynamic languages make for easier to refactor code. That might be true, but it doesn't have to be so bad in practice when you keep your interfaces very small and focused.
- Most things you want to express can be expressed in a static language
- Tooling is much easier to build over static languages, and I think automated checkers are the future of rapid development of robust programs
I don't think that OOP languages as they are now (particularly Java 8) are the future, but something with less ceremony like an ML. Java and C# might flourish in the long term by becoming ML languages, but only if they are prepared to remove the cruft.
wtf argument
Stack Overflow's annual survey puts JavaScript, SQL, and Python at the top, with C at 12th [0]. RedMonk's Top 20 puts JavaScript, Python, and Java at the top, with C in 10th [1]. ITJobsWatch puts JavaScript, SQL, and C# at top, with C at 9th [2]. Dice puts SQL, Java, and Python as its top 3, with C not even ranking in their top 12 [3]. All of those put JavaScript, Java, and Python in the top 5.
[0] https://insights.stackoverflow.com/survey/2021#most-popular-...
[1] https://redmonk.com/kfitzpatrick/2021/03/02/redmonk-top-20-l...
[2] https://www.itjobswatch.co.uk/default.aspx?ql=&ll=&id=900&p=...
[3] https://insights.dice.com/2021/01/05/top-12-programming-lang...
I think at least for UI work there is a lot of space for dynamic plumbing together of well typed components. Components in this case meaning actual UI components as well as modules of business logic or state management.
On personal projects I only want to deal with builtin browser technologies, there is no npm, webpack, tsc, yarn, whatever, just plain <script/> tags.
Also the scale of the software matters, types are more important in larger systems. Single developer systems tend to be small.
For a compiler that can compile even with errors in the code, look at ECJ.
If you take HotSpot and attach a debugger in your IDE, then you have some hotswap capabilities [1]. You can redefine the contents of methods, add methods and add classes (e.g. lambdas). This is OK as far as it goes. But this is no inherent limitation of Java. In fact the debugger protocol lets you request arbitrary changes, it's just not all JVMs support them.
One that does is called DCEVM [2]. It fleshes out the hotswap capabilities far more extensively and lets you do things like delete methods, change prototypes, alter the inheritance hierarchies etc, all on the fly whilst the app is loaded and running.
DCEVM is an open source patchset onto HotSpot, but it's not really a pro level tool. JRebel [3] is a company that makes hotswap tools as a commercial product. Many companies use it.
These are a neat capabilities and I've used them a few times, but even with that level of power, it's not always complete for every use case. The problem is that most apps have initialized state. Web servers often do not, because they throw away state at the end of every request, and there it works better, but if you're working on e.g. a GUI or a CLI tool with a shell, or really anything where the program has to maintain state for longer than a split second, changing code becomes of more limited use because you are going to end up changing initialization code that won't re-run. You can add various ad-hoc hooks to your app to let you force re-init whilst running, but it's not totally smooth. Note: this isn't a limitation of the language or runtime. It's inherent to the concept of hotswapping code.
There is work to resolve even this problem. The Espresso JVM has full hotswap support, and a callback interface that lets the app learn when its own code is being redefined. It can use those callbacks to trigger re-initialization of any state that's required. [4] Espresso is still new but this sort of thing lights the way to apps that perhaps never need to be shut down at all, not even for upgrades.
[1] https://www.jetbrains.com/help/idea/altering-the-program-s-e...
[3] https://www.jrebel.com/products/jrebel
[4] https://www.graalvm.org/reference-manual/java-on-truffle/hot...
Whereas with Java majority of the time things work first try because any trivial type issue have been sorted already by the compiler.
I often wonder how much time (== money) I waste debugging existing code which has a logic error that would have been caught by any type system, or trying to piece together the type of some variable when writing new code. I expect it’s significant.
No. And neither will screws replace nails.
Amen.
One could also make the opposite and not contradictory point that type-systems make unit-tests less needed.
They both help
Will this article disprove the rule that whenever the headline is a question, the answer is always no?
Also no.
I recently wanted to make a simple enough PR to a large JavaScript codebase to fix a bug. After a few hours I found where the call was happening and what changes I needed to make.
At a simple level the code update was "measure the length of each of these things and store them, for each of the stored things align them relative to the longest length of stored items and add them to the state".
It took about 3 times longer to get to working code because of the lack of types. "Oh, you've used `i` in some context, you must just mean a global of indeterminate type, better keep running. Oh you forgot whether the method name on type of string is SubString or Substring? Sorry can't help you, don't know what a string is. You don't know/remember what you can do with this variable? Neither do I!" Sure you can have linters or whatever to catch these stupid mistakes but I'd rather just have the bloody thing work first time.
I'd rather have my tools assist me than feel like an alpha-chad because I've managed to memorise the entire API of something. I have more useful things to keep in my brain. Sure it might let you go quickly in your 50 line script but woe-betide any developer who comes later.
The raise of unit testing in the early 2003-2006, coincided with the raise of popularity of the Python web frameworks and Ruby on Rails. Suddenly Unit testing became a necessity, while previously it was a 'nice to have', as static typing covered a lot of the errors that dynamic languages introduced. Before 2005, in most places, 'integration testing' was the norm, but not unit testing.
In the other hand, Objective-C took a very interesting turn, where it is a static typed language, but it is message oriented, and you can use it in a semi dynamic typing way. You can send a message (method call) to any object, which allows for interesting compositions (eg. [(id)myObject anyMethod] ). Calling a method on a nil object, doesn't raise exceptions, etc...
I thought it made an awesome compromise. Unfortunately, Swift went the opposite way, which I didn't think was the right call. (as Java already covered that area well). Hence Swift hasn't taken off, appart from iOS as it didn't really introduce anything new, just little soup of paradigms that don't fundamentally make things much better. It was a missed opportunity.
I think size becomes a problem when you don’t properly modularize and test.
Also I think often it is more about the specific language in use rather than dynamic vs static typing. I would rather use Go than JavaScript. But I would use Julia over almost anything else when possible.
The theory that unit tests started happening around the rise of Python and Ruby is vague, unsubstantiated and intellectually lazy.
I actually remember the rise of TDD being intimately related to the enterprise world and Java but I’m certainly not going to pass that as scientific fact.