by seanwilson · 5y ago · 0 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...
In contrast, a compiles-to-JS language can produce code that behaves unexpectedly in its non-functional requirements, and in the worst cases crashes where it shouldn't. That will be less of an issue as compilers get better, and WASM should help a lot, but in the current ecosystem TypeScript produces more predictably good results.
I should also note, I've attempted OOP in TS and it wasn't pretty. It is much more suited to a functional style IME, although I will concede I have seen some open source projects that use it in a Java-esque OOP style presumably to good effect. Personally it wasn't my cup of tea.
If you are curious about this, you might be interested in checking out Haxe [0]. It has static typing, type inference, pattern matching [1] (maybe not on par with ML languages, but still good), and can transpile to multiple targets [2] including JS.
[0]: https://haxe.org [1]: https://haxe.org/manual/lf-pattern-matching.html [2]: https://haxe.org/documentation/introduction/compiler-targets...
Expand please?
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.
Not once have I done this. I've written plenty of invariants that would have been covered by a static type system but no tests.
As far as I'm concerned if you had to write an extra test to "cover for a dynamic type system" that test is a bad smell that should be deleted. A test validates that a method raises an exception when being fed a null is pointless if it's just testing a one line assertion that does the same thing. It's a waste of keystrokes. It doesnt catch bugs.
There may be some exceptions to this rule but they would be under very obscure circumstances, I think.
They obviously work best when "combined with test coverage" but then again, I dont consider test coverage to be "optional" in any language. This idea that "if it compiles it works" that some haskellers seem to believe, for instance, is complete horseshit.
If somebody argues that static typing works great because without tests it catches more bugs than dynamic typing does when you also dont write tests, it's notionally true, yes, but theyre telling you more about themselves than they are about types. Namely that they're not in the habit of writing tests.
If you've got enough of the right kind of testing coverage to validate an app written in a statically typed language you will have enough to trigger invariants in a dynamically typed langauge.
I have successfully had invariants usefully triggered in prod and by manual testers in big balls of mud without test coverage (failing fast isnt just for test environments) but I considered that to be a form of emergency programming CPR and damage limitation that isnt a substitute for fixing your testing "diet".
Clojure does have spec (https://clojure.org/about/spec) which is pretty cool and declarative. And, of course, your IDE can help you when writing code that obviously violates a spec declaration. But that's not fundamentally different from an IDE parsing the type-hints of Python, JavaScript, or PHP. It is more powerful than the aforementioned type-hints, though.
At the end of the day, it blurs the line between static typing and dynamic typing. IMO it should be considered static typing because it serves that same purpose, works at "write time" to help the programmers, and can probably absolve you of writing your own type-checking tests.
In some sense, it is all just asserts. Even statically typed languages have unsafe type casting, which can trigger an "assert" at runtime.
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'JavaScript's more forgiving, and often surprising, implicit conversions are still rigidly-defined .
Remember that implicit conversions should never (ostensibly) throw any exception or cause any errors because implicit conversion should always succeed because it should only be used to represent an obvious and safe narrowing-conversion. A narrowing-conversion necessarily involves data-loss, but it's safe because all of the data needed by the rest of the program is being provably retained.
class A(random.choice([B, C]):
...The last thing: being able to edit program code, add new types/members/functionality and so-on while it's running... that's not really a language limitation nor typing-system limitation either: that's just good tooling that is able to hot-swap executable code after the process has already started. Visual Studio has had "Edit & Continue" in debugging sessions for almost 3 decades now, and the runtime build system used by ASP.NET means that source code and raw aspx/cshtml views can still be FTP'd up to production and just work, because .NET supports runtime compilation.
------------
For ordinary business software, where the software's focus is on data-modelling and data-transforming-processes, so all these programs basically just pass giant aggregates of business data around, so strong-typing is essential to ensure we don't lose any properties/fields/values as these aggregate objects travel through the software-proper. In this situation there is absolutely no "expressiveness" that's could be gained by simply giving up on type-correctness and instead rely on unit tests (and hope you have 100% test coverage).
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.
Sure, but if your typed language is sound you shouldn't have type errors at runtime. Not having type at runtime is not a problem, type erasure is nothing new and works really well in OCaml.
> 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.
Rescript and Elm are really solid, OCaml can compile to JS too, Scala and F# too. Granted, only Elm has been built on JS at first, others were adapted (Rescript is like half and half), but they're all solid.
> 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.
I think the idea here is to offer WASM as a compilation target. Trying to gradually type JS leads to really complex systems (TS types) because people did all sorts of crazy things with JS. I wouldn't like this to be the base on which we build other languages, or the web in general.
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.
If it's an external API, do the same thing except it probably needs a more manual approach.
This is not something that's in anyway unique to typescript. The difference is JavaScript is designed to fail gracefully using coercion whereas most other languages and runtimes abort and throw exceptions.
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.
In particular, we can use dependent types to place much tighter constraints on critical pieces of code, but 'cut short' a full correctness proof by simply punting to an error case when it's convenient.
For example, say we need to manipulate the Nth element of a collection. We can express indices with a type 'Fin X', whose values are equivalent to 1, 2, ..., X, e.g.
f1 : (c: List Foo) -> (n: Fin (length c)) -> BAR
Within this 'f1' function, we know that the index 'n' will appear in the list 'c' (as a corollary, we also know that 'c' is non-empty, since empty lists have no indices!); this lets us specify the intended behaviour more precisely, lets us satisfy the requirements of other functions we may want to call, lets the compiler spot more problems for us, perhaps avoids the need for certain bounds checks, etc.Yet this places a burden on anyone who calls this 'f1' function: they need to prove that the index appears within the list (and, in doing so, prove that the list is non-empty). This might be very difficult in the general case, yet a full correctness proof would require it.
However, we don't need a full correctness proof; so we can just check if we're in bounds, and return an error if not:
f2 : List Foo -> Int -> Either String BAR
f2 c i = case mkFin (length c) i of
Just i -> Right (f1 c i)
Nothing -> Left ("Index " + show i + " not in list of length " + show (length c))
where mkFin : (n: Nat) -> (i: Int) -> Maybe (Fin n)
mkFin Z _ = Nothing
mkFin _ i | i < 0 = Nothing
mkFin (S n) 0 = Just fZ
mkFin (S n) i = map fS (mkFin n (i - 1))
Calling a function like 'f2' may end up hitting the error case, so this doesn't prove our entire application is correct; but we can still prove all sorts of things about 'f1', and hence have a lot of confidence in what happens whenever this initial error branch is avoided. Also, anticipating an error up-front is usually preferable to hitting one half-way through processing.Dependent types are really useful for propagating error conditions 'backwards' through the code like this. When practical, I much prefer this to propagating error conditions 'forwards', by returning Maybe, etc. Most applications start with some sort of parsing step, which is a great place to perform such checks, if we can manage to propagate them back that far. Otherwise, we just handle these error cases just like we would any others (dependent types or not).
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.
The problem with stringly-typing is the model, which is SQL as strings. Statically type-checking that all your strings are, in fact, strings does not buy you anything whatsoever in this scenario.
On the other hand, if you have an actual model of the SQL, then it also doesn't matter whether that model is checked at runtime (dynamic typing) or at compile-time (static typing). In either case it will not allow injection attacks, if implemented correctly.
And of course the actual place where nastiness happens is the user input, and I haven't yet seen a place that can statically typecheck users. ;-). So, as you point out, you will need to do dynamic checking and sanitising of input.
My gut tells me that's not quite right (for some reasonable definition of 'usable'), since we can always build elimination forms into the language (after all, 'null' must be built in, and few take objection to building in elimination forms like if/then/else).
> it also requires some kind of pattern matching or monad comprehensions - otherwise, code using Optional is neither type safe nor readable.
I really like comprehensions in Python, but hardly ever use them elsewhere. In fact, when I do use them in Haskell and Scala, I usually find myself having to refactor them into calls to `map`/`join`/etc. soon after, to have more fine-grained scoping or somesuch.
> trying to offer a generic SQL library that presents an AST as the API for even the most popular RDBMSs quickly gets complex
That's orthogonal to anything I said. Represent SQL using arrays of bytes in memory if you like; offer a string-like interface for constructing and manipulating them if you like; just make sure to distinguish them from other string-like types, in a way that's statically enforceable, and where the only API to convert a 'String' to an 'SQL' is the escaping function.
Note that I don't particularly care if an SQL value is valid; it would be nice to statically enforce that, but you're right that (vendor-supplied) SQL is pretty complex in its own right. What's much more important to get right is that SQL is not user-generated.
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).
"SafeStrings: Representing Strings as Structured Data"
https://arxiv.org/abs/1904.11254
Bosque
https://github.com/microsoft/BosqueLanguage/blob/master/docs...
This sentence betrays a confusion about what types are, and how to use them. In particular, you seem to be mixing up two possible scenarios.
In the first scenario, we have a method which "wants a string" (i.e. its input type is 'String'), and we can "pass a string" (i.e. call it with an argument of type 'String'). This code passes the type-checker, since it implements the specification we gave: accept 'String'. Perhaps there are higher-level concepts like "formats" involved, and the resulting application doesn't work as intended; but that's not the fault of the types. More specifically: typecheckers verify that code implements its specification; but they do not validate that our specification captures the behaviour we want.
In the second scenario, we have a method which "wants a string in a particular format" (i.e. its input type is 'Format[A]'), and we "pass a string in another format" (i.e. call it with an argument of type 'Format[B]'). That is a type error, and the typechecker will spot that for us; perhaps pointing us to the exact source of the problem, with a helpful message about what's wrong and possible solutions. We do not get a runnable executable, since there is no meaningful way to interpret the inconsistent statements we have written.
tl;dr if you want a typechecker to spot problems, don't tell it that everything's fine!
If you want the safety and machine-assistance of such 'Format' types, but also want the convenience of writing them as strings, there are several ways to do it, e.g.
- Polymorphism http://okmij.org/ftp/typed-formatting/FPrintScan.html#print-...
- Macros https://www.cse.iitk.ac.in/users/ppk/teaching/cs653/notes/le...
- Dependent types https://gist.github.com/chrisdone/672efcd784528b7d0b7e17ad9c...
> A method that wants an integer in a range. An array of maximum N elements. And we can go on forever.
You're making the same mix-up with all of these. Fundamentatlly: does your method accept a 'Foo' argument (in which case, why complain that it accepts 'Foo' arguments??!) or does it accept a 'FooWithRestriction[R]' argument (in which case, use that type; what's the problem?)
Again, there are multiple ways to actually write these sorts of types, depending on preferences and other constraints (e.g. the language we're using). Some examples:
- https://hackage.haskell.org/package/fin
- https://ucsd-progsys.github.io/liquidhaskell-blog
Your "integer in a range" is usually called 'Fin n', an array with exactly N elements is usually called 'Vector n t', etc. I don't think there's an "array of maximum N elements" type in any stdlib I've come across, but it would be trivial enough to define, e.g.
data ArrayOfAtMost Nat (t: Type) where
Nil : {n: Nat} -> ArrayOfAtMost n t
Cons : {n: Nat} -> (x: t) -> (a: ArrayOfAtMost n t) -> ArrayOfAtMost (S n) t
This is exactly the same as the usual 'Vector' definition (which is a classic "hello world" example for dependent types), except a Nil vector has size zero, whilst a Nil 'ArrayOfAtMost' can have any 'maximum size' we like (specified by its argument 'n'; the {braces} tell the compiler to infer its value from the result type). We use 'Cons' to prepend elements as usual, e.g. to represent an array of maximum size 8, containing 5 elements [a,b,c,d,e] of type 'Foo', we could write: myArray: ArrayOfAtMost 8 Foo
myArray = Cons a (Cons b (Cons c (Cons d (Cons e (Nil 3)))))
Note that (a) we can write helper functions which make this nicer to write, and (b) just because the code looks like a linked-list, that doesn't actually dictate how we represent it in memory (we could use an array; or we could optimise it away completely https://en.wikipedia.org/wiki/Deforestation_(computer_scienc... )I actually wrote a blog post many years ago which goes through various types which have a similar 'Nil and Cons' structure http://chriswarbo.net/blog/2014-12-04-Nat_like_types.html
Also note that we don't actually need to write such constraints directly, since we can often read them in from some external specification instead (known as a "type provider"), e.g. a database schema https://studylib.net/doc/18619182
> you end up doing things only to make the compiler happy, even if you know that a particular condition will never happen
You might know it, but the compiler doesn't; you can either prove it to the compiler, which is what types are for; or you can just tell the compiler to assume it, via an "escape hatch". For example, in any language which allows non-termination (including Idris, which lets us turn off the termination checker on a case-by-case basis), we can write an infinite loop which has a completely polymorphic type, e.g.
-- Haskell version
anything: a
anything = anything
-- Dependent type version
anything: (t: Type) -> t
anything t = anything t
We can use this to write a value of any type the compiler might require. Even Coq, which forbids infinite loops (except for co-induction, which is a whole other topic ;) ) we can tell the compiler to assume anything we like by adding it as an axiom.> 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).
Static types certainly give a compiler more information to work with; although whether the resulting language is faster or not is largely orthogonal (e.g. V8 is a very fast JS interpreter; Typed Racket not so much).
As for merely using a type system for linting, that's ignoring most of the benefits. No wonder your code is full of inappropriate types like "string" and "int"! I highly recommend you expand your assumptions about what's possible, and take a look at something like Type Driven Development (e.g. https://www.idris-lang.org )
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).
You are confusing "type" with "not a function type".
Firstly, I absolutely want to check, statically, that my user input is `ByteString`, or `String`, or some more distinguished newtype/AnyVal wrapper around those. If that doesn't pass the type checker, I would be very worried about ever starting such an executable!
Other than that, I want to check, statically, that my functions conform to their type signatures. When I write `parsePNG userInput: Maybe PNG`, not only do I want to make damn sure that `userInput: ByteString` is definitely a `ByteString`; I also want to make damn sure that `parsePNG: ByteString -> Maybe PNG` is definitely a (partial) function from `ByteString` to `Maybe PNG`. If I can't guarantee, without executing the program, that `parsePNG` can only return `Maybe PNG` values, then all bets are off regarding downstream invariants, and that's not a good situation to be in w.r.t. security vulnerabilities.
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.
But when you start having loops, conditions, arrays, nullable references etc. you can't be so confident any more unlike with proper type checking where you can be fully confident.
What you have, after manual inspection of the code, is some sort of informal and not written down correctness proof. A machine tested proof would be better and types help with that.
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.
I have no idea what you're going on about. The customer doesn't care about the particulars of your unit or integration tests, instead they care about whether your software works properly. A modern, powerful static type system is one tool that helps a developer achieve that goal of properly working software, and the developer absolutely should care about whether that function argument is an integer or a string.