by lisper · 4y ago · 0 comments
It happened thirty years ago:
https://en.wikipedia.org/wiki/The_Art_of_the_Metaobject_Prot...
But the thing that really drives me nuts about this never-ending debate is that static and dynamic are not a dichotomy. You don't have to choose one or the other. You can have both.
The real choices are:
1. Do you want the language to require the coder to provide type information (e.g. Java), or permit the coder to provide type information (e.g. Common Lisp) or forbid the coder from providing type information (e.g. early versions of Python, Javascript).
2. How much work do you want the compiler to do with regards to finding potential problems at compile-time, and what do you want it to do when it finds one? Options include: do nothing (e.g. Javascript), warn if it finds a problem (e.g. C), or forbid you to run the program if it finds one (Java, Haskell).
Personally these choices have always seemed like no-brainers to me: allow but don't require type information, and warn when the compiler finds a problem but allow the program to run anyway. What possible advantage is there to be gained from any other choice?
You're thinking like a single individual. Almost all programming that happens in the real world is in teams, and most of that probably within companies.
Teams and especially companies often benefit from strict standards that keep everyone on the same page and make it harder to screw things up.
Sure, but those standards don't have to be enforced by the language design. They can be enforced, for example, by policy, e.g. "Don't push anything that produces warnings to the master branch". That still allows you to, for example, test parts of an uncompleted program, which can vastly improve productivity. Not being able to test-run a partially completed program can increase your development cycle by orders of magnitude.
Which is usually either no-one, or an already busy/overloaded team lead or (even worse) manager.
Every software engineering organization I’ve been at either wanted, or put in place, automated policy enforcement because otherwise it either never happened (and hence there were constant problems), or everyone hated doing it because it felt like a waste of their time (with it’s own constant source of problems).
it’s best for everyone if a problem is identified and called out as close in time to when it’s created as possible, and as clearly as possible. Ideally before it can be part of any product, or be depended on by other work that would need to be refactored.
Which automated tools can do cheaply. If it is in the compiler, even better!
Doing it manually delays the feedback cycle, AND burns people decision energy, which is almost always the thing everyone is in the shortest supply of anyway.
Sure. But it does not follow that it is beneficial for your language to forbid you from testing some code you wrote over here until you fix a completely unrelated problem over there, indeed until you fix every single problem that the compiler can find.
> Doing it manually delays the feedback cycle
I'm not talking about "doing it manually", I'm talking about the compiler issuing warnings instead of errors.
CI/CD, based on CTO edict? Have them (or their startup equivalent) make the edict at the start of the company's lifecycle for best results.
Don't make it a human procedure, make it a "you're physically unable to deploy until tool X doesn't throw a warning". Anything else will, as you say, fail.
Yes, policy debates are amazing, so fun, so productive. And nothing funnier than having to discover completely new and incompatible policy when changing company, or trying to change policy.
That's one of the few good things I have to say about Go, they considered policy debates and went "fuck that". I think they went too far and wrong in lots of ways, but on that front I can't fault the heart, even if I hate the language.
Who says there's going to be a debate? The commit hooks and/or CI pipeline should prevent you from merging code that doesn't pass typecheck. It's still enforced by tooling, just at a different place in the process.
I laughed out loud when I read this.
Funny thing is, this would work where I'm at now, Google, because Google actually has an enormous number of presubmit checks that require all KINDS of things out of your code, it's practically crazy how many checks it runs. Since there's already so much setup for these checks, yeah adding one more would be fine (and it already does this for type annotations for dynamically typed languages like Javascript).
But most places aren't Google, and it's way more realistic to prevent this kind of problem by just having a language that'll enforce it automatically, then you never have to think about it, or have a policy debate, or always make sure during code review to look for that thing, etc.
If I'm putting out some small open source library where I might get an occasional pull request, I'd much rather have the language automatically enforce correct typing than have to remember to look for it myself every time (and then possibly miss something if I screw up).
All that being said, your point is a valid one. It's a tradeoff and depending on what you're used to, you'll feel the pain from one approach or the other more strongly.
I have never worked on a project that has actually followed such advice.
This sounds insane to me. Do you really think needing to specify types up front saves you that much time?
Multiple orders of magnitude means you're talking a 100x speedup at minimum.
For example, making unused function arguments a fatal error would be an easy place to increase iteration time.
Then the following arguments are moot, as CICD will run it in the “sane default” setting.
Your compiler giving you a type check error is saying that the program is meaningless. What is the advantage of running a program that is known to be wrong?
The design of the type system will define what is meaningful/meaningless per type check rule (eg a missing branch which can be a warning vs an ambiguous type inference that means the program cannot be compiled). The question is really whether you want to design a type system that can be checked statically, which to me the no-brainer answer is "yes."
I don't want to have to run the program to know if it type checks. I don't want to have to run it to know what types are in the program, or the signature of functions. I want my tool to tell me when my code is provably wrong, and to prevent provably wrong code from being merged into a codebase without executing it.
The TypeScript compiler will absolutely give you errors for well-formed programs that are guaranteed* do the right thing with respect to what the author intended and that anyone else can see is correct but that the TypeScript compiler itself doesn't reason about correctly. In instances where this happens, it's very useful to be able to ignore them—just like you might ignore the protests of a misinformed team member who insists that such-and-such won't work, even though it provably will. (Although the alternative of just not using the TypeScript compiler can be a worthwhile decision as well.)
* not to be confused with undefined behavior in C where it might just happen to work with one known compiler/platform combo but break horribly for other valid targets
For example, TypeScript explicitly declares as a design goal that they don't use the type system to generate different code:
https://github.com/Microsoft/TypeScript/wiki/TypeScript-Desi...
Meanwhile in Dart, you can write:
double d = 1;
In Dart, doubles and integers are different types with different representations. The above line of code works because if we see an integer literal in a context where a floating-point number is expected, we implicitly treat it as a double literal. Note that there's no runtime conversion here. We can do this because Dart does have a sound type system and is happy to use it for language features.That's also why Dart (and other statically typed languages) support extension methods while TypeScript does not:
https://github.com/microsoft/TypeScript/issues/9#issuecommen...
If the language gives users the ability to type their code, it's really nice to be able to give them as much value in return for their effort. That means building language features on top of them and using types to generate smaller, faster code.
But languages with unsound type systems or that treat programs with type errors as well formed can't really do that.
Well one bit is you might not be looking at the meaningless part.
Sometimes when doing large refactorings or updates never getting to run, try, or look at anything is discouraging. It's a great feeling when it compiles and everything works (or near enough), but spending two days cycling between compiling and fixing compilation errors is not as enjoyable as e.g. seeing the unit test report's green bar tick up.
Maybe compilers should provide more enjoyable feedback, not just better error messages (though I fully support that movement).
What's the difference between seeing a bunch of test failures and fixing them one by one until the test suite is all green, and seeing a bunch of compiler errors and fixing them one by one until the compiler runs clean?
For example, you might not be pushing buttons that trigger the meaningless part, but the other parts of the system might still be functional.
> What's the difference between seeing a bunch of test failures and fixing them one by one until the test suite is all green, and seeing a bunch of compiler errors and fixing them one by one until the compiler runs clean?
The difference is in one of the cases a highly qualified professional has freedom to decide _when_ to do the fixes.
Speaking of which, that WOULD be a cool IDE feature. I always liked the feeling of my junit bar going all green after a big change.
I can't think of many worse experiences than my past self trying to refactor Python 2 code. Compared to _any_ type system it's just not even close.
Like updating data structures should never result in days of work before you can run simple tests. Create a new build artifact that only pulls in the new data structures and the software modules you're working on (and their tests). If you need to pull in the universe to run any unit tests, they aren't unit tests.
Substantially better performance, which still matters in some domains.
If you occupy any space on the spectrum besides fully static typing, you must represent and check your types at runtime. This means that every object (even Int and Bool!) needs to have a header that tells the runtime what type it is, which can quite literally double your RAM requirements.
If a language is already including object headers anyway (like Java does), you're correct that there's not an enormous barrier to embracing gradual typing [0]. But there are a lot of places where we really do still care about RAM usage, and erasing types at runtime is an obvious place to free up a lot of RAM very quickly.
[0] Indeed, you can sort of do this in Java already by just typing everything as Object and coming back later to correct it with actual types, though please don't actually do this.
If the language requires you to give at so much type information that the compiler can infer all the types, I would say that language, from the compiler’s view, would have fully static typing, so it wouldn’t have to do any checks at runtime, but from the programmer’s viewpoint, it could look as if it didn’t have fully static typing.
The modern auto to deduce a type in C++ makes a small step towards that, but I think it could be taken further. The language could deduce types both in the direction “if you pass foo to a function taking an integer, it must be an integer” and “if you only pass integers to bar, bar must take integers”.
I expect it will be hard to specify a powerful algorithm for filling in the blanks that feels natural to programmers, though. If the compiler frequently complains about missing type information where the programmer doesn’t understand why it complains, the language won’t be popular.
This is the problem in a nutshell. Folks in the optional typing and gradual typing communities have been trying to pull this off for decades and so far no one has been able to come up with a language that:
1. Lets you ignore types completely and write dynamically typed code in some parts of the program.
2. Gives you the expected performance of completely typed code in parts of the program that are typed.
3. Is sufficiently pleasant to use that it gets adoption.
There are languages that give you either 1 or 2 along with 3. There may be some language out there that gives you 1 and 2 but if so, it doesn't give you 3 or I would have heard of it.
I suspect it's intractable.
However, better type inference does not mean that a language is no longer statically typed, it just moves a lot of the burden of assigning types from the programmer to the compiler. You still don't have as much flexibility at runtime, and you still can't run your code until the compiler can prove that it it correctly typed. The only thing you get is less syntax, not dynamic semantics.
Liberties are rarely created and destroyed. Instead, they tend to be trasferred from one place to another. So an equally valid way to phrase this question is from the compiler's perspective:
1. Do you want the compiler to be able to rely on the presence of type information (e.g. Java), or sometimes have access to type information (e.g. Common Lisp) or be forbidden from using type information (e.g. early versions of Python, Javascript).
In that equivalent formulation, the value proposition of static types is clearer: When the language specifies that everything has a computable static type, then the compiler can rely on types for useful language features (extension methods, overloading, static dispatch, etc.) and to generate smaller, faster code.
Dynamic types give the programmer some liberties (they can not worry about types) but takes some others away (they can't reach certain performance goals or use type-dependent features). Static types do the opposite. Pick your poison.
A pseudocode example is something like:
trait ToString for T {
fn toString(self: T) -> String;
}
impl ToString for number {
fn toString(self: number) -> String {
// implementation here
}
}
impl ToString for Point {
fn toString(self: Point) -> String {
return f"({self.x.toString()}, {self.y.toString()})";
}
}
fn printString<T: ToString>(t: T) {
print(t.toString());
}
Then when it generates code, it uses the inferred type information to generate different code: let p = Point(1.0, 2.0);
printString(p);
// translated into
printString(implToStringForPoint, p);
let n = 2.0;
printString(n);
// translated into
printString(implToStringForNumber, n);
And then type inference becomes implementation inference, which is really powerfulI would argue that something like "dynamic" is preferable in a sense that it gives you an escape hatch with minimal syntactic overhead for those cases where dynamicity is really that beneficial, yet defaults to a safer option that's usually the best choice.
I guess the part where it will also pick the correct overload at runtime depending on the actual type of the arguments is a bit like multiple dispatch, especially if the argument itself is "dynamic". I'd say that the difference is that the list of possible candidates is closed once the class is defined, so even if you declare a new type, you can't customize the behavior when passing it to an object of an existing class.
If you're the only one writing the entire stack of code that gets bundled into the delivered program, you're right, no real advantage from other choices.
But as that's rarely the case, there is a lot of advantage from having a forced type system. Otherwise your code might be great but you're pulling in libraries and code from many other teams who chose to omit type info and/or ignore all warnings so you still have the same problem.
This is actually a really great argument. Having well-typed dependencies is a real benefit. But I would say you don't need to force typing on people to achieve that. In my experience with gradually typed languages (TypeScript and Erlang) you tend to see decent adoption of typing in prominent libraries. There are natural incentives (i.e. crashing software) that drive people away from depending upon libraries that don't have strong type guarantees.
I've been meaning to write up something comparing dynamic typing + SLIME to -fdefer-type-errors and ghcid...
I was with you until your last sentence. The world of programming is a lot bigger than your tiny corner of it.
I could be working in a safety-critical situation, where preventing errors is more important than developer velocity.
Or, I could just have that one annoying co-worker who checks in stuff that "works for him", but always crashes when others try to use it.
Or...
I am not aware of any static languages that check the types at runtime (if such languages exist, please mention them in the comments); however. they require a static analysis to happen at compile time, and refuse to compile if the analysis breaks at any point. Python, on the other hand, allows to be compiled and executed without ensuring the type safety first; however it can still be statically analyzed, even without explicit type annotations, using an optional tool such as mypy (which can infer types quite correctly in many cases).
For example, Java will throw an exception at runtime if an object is cast (using .asInstanceOf) to an incompatible class. Python throws if you add an integer to a string. Both of those languages are strongly typed.
On the other hand, C has no runtime checks whatsoever. If you add a number to an array the program will happily move the array pointer and maybe overflow, but even that won't cause a runtime failure every time.
I expect this must be fairly common among IDEs with incremental compilers. You can run valid sections & gradually progress the complete correctness. No need for a dynamic language.
With static typed language, reliability and refactoring are easy.
I'm scripting some small scripts in Python this week but every time I come back to it, I am reminded how not actually very good it is.
1. The program is in fact correct, but the typechecker can't prove the program is correct and so reports it as a failure (for contrast other typecheckers only report errors if it can prove that there is an error)
2. The type checker is correct in that the program is flawed in some way, but you are the middle of development and it would be more productive if you could observe the behavior of the program before fixing the types. Since your CI pipeline will fail on type errors it's not like you're going to be able to merge your changes before fixing them.
3. The program is incorrect but correct for all expected end user inputs.
One of the most annoying things moving from Ruby / Python into a language with static types that are checked at compile time is dealing with JSON from an external API.
I know, I know. The API could send me back a lone unicode snowman in the body of the response even if the Content-Type is set to JSON. I know that is theoretically possible.
But practically, the endpoint is going to send me back a moustache bracket blob. The "id" element is going to be an integer. The "first name" element is going to be a string.
Sometimes a disable-able warning is all we want.
Because e.g. in Rust what you're talking about is:
#[derive(Deserialize)]
struct Whatever {
id: usize,
first_name: String
}
// ...
let thing: Whatever = get(some_url)?.json()?;
You encode your assumptions as a structure, then you do your call, ask for the conversion, get notified that that can fail (and you can get an error if you but ask), and then you get your value knowing your assumptions have been confirmed.It's definitely less "throw at the wall" than just
thing = get(some_url).json()
but it's a lot easier to manipulate, inspect, and debug when it invariably goes to shit because some of your assumptions were wrong (turns out `first_name` can be both missing and null, for different reasons).For a 5 lines throwaway script the latter is fine, but if it's going to run more than a pair of time or need more than few dozen minutes (to write or run) I've always been happier with the former, the cycle of "edit, make a typo, breaks at runtime, fix that, an other typo, breaks again, run for an hour, blow up because of a typo in the reporting so you get jack shit so you get to run it again".
And within the bounds of pragmatism, it's nice that it actually checks this stuff and throws exceptions. In Ruby if the ID field is the wrong type, the exception won't happen at time of JSON.parse(...) but instead much later when you go to use the parsed result. Probably leading to more confusion, and definitely making it harder to find that it was specifically an issue with the JSON and not with your code.
That doesn't make much sense - either the API has a well-defined schema, and you define your static types to match (which there are usually tools to do for you automatically, based on an OpenXML/Swagger schema, if there isn't already an SDK provided in your language of choice), or you use a type designed for holding more arbitrary data structures (e.g. a simple string->object Dictionary, or some sort of dedicated JsonObject or JsonArray type).
There are issues around JSON and static typing, e.g. should you treat JSON with extra fields as an error, date/time handling, how to represent missing values etc. (and whether missing is semantically different to null or even undefined), but I would hardly see it as "one of the most annoying things".
Edit: the other issue I forgot is JSON with field names that aren't valid identifiers, e.g. starting with numerals or containing spaces or periods etc. But again, not insurmountable. I'd actually be in favour of more restrictive variation of JSON that was better geared towards mapping onto static types in common languages.
With code gen you can usually just print out your JSON directly from the source and import that as a type into your source code.
This is why apis are moving towards specifications that trigger multiple generators.
JSON typing is possible without generation, but more cumbersome.
interface TypedJSON {
string?: string;
number?: number;
array?: TypedJSON[];
boolean?: boolean;
object?: {[key: string]: TypedJSON}
}{foo: {string: "my string"}, bar: {number: 4}}
Probably makes sense to make the "string" key "s" for minimal payload size impact, or this could also be done by converting standard JSON to this typed representation at runtime.
It's not pretty but it can be done. :P
Sometimes I don't care which political party the barista voted for, I just want to get my coffee.
People and programs are never perfect. Type checked program is not guaranteed to be correct, it just has stronger constraints.
Per #2, why not a language that facilitates "lint" style inspectors to give a list of warnings, as in "do you really wanna do that?" This reduces the burden of the compiler. Meta-markers can switch certain warnings off so we don't clutter the results for intentional spot looseness.
And as GHC actually has a compilation mode where it only warns about compilation errors: https://gitlab.haskell.org/ghc/ghc/-/wikis/defer-errors-to-r...
So they're 0/2, on the subject they're espousing upon, through a language they mentioned.
The GP asked what’s the point of languages like this. The two massive advantages in my mind are that compiled programs are usually correct, and compiled programs run really fast. I often have the experience in rust of writing hundreds of lines of new code, and my program works perfectly the first time I run it. That’s a delight.
It has to do with documentation, intent, and clarity. Also clarity of error messages, compilation errors with generic functions under GTI are as bad as C++ template errors.
I wish it were common [0] for source code to show a combination of programmer-specified and compiler-deduced details.
Seems like we could get the best of both worlds.
[0] I know some IDEs show e.g. type information as mouse-over text. I'm talking about something that integrates more cleanly into the actual source-code text. So, e.g., it would show up when diff'ing the source code.
This is absolutely false. Compiled programs might be correct with respect to type safety, but that is very different from being correct. There are all kinds of ways that programs can fail besides type errors.
In fact, this widespread false belief is IMHO one of the strongest arguments against using enforced-compile-time-strong-typing because it lulls you into a false sense of security. I have a long list of war stories where this led to problems that ranged from annoying to very nearly catastrophic.
Yes, you still need tests. But testing is never perfect. Bugs still slip through. I like not needing to be as paranoid in rust as I am in other languages.