For four days, I spent debugging a python production script because in one place I had typo'd ".recived=true" on an object and just couldn't understand why my state machine wouldn't work.
And very quickly, the whole team became fans of __slots__ in Python.
I still write 90% of my useful code in python, but that one week of debugging was exhausting & basically wouldn't have even compiled in a statically declared language. Even in python, the error is at runtime, after I got the __slots__ in place.
Is that really a dynamic typing problem or a language that allows you to create instance members anywhere? It seems like that is a flaw in the declaration model of the language and not a static / dynamic issue.
$ txr
This is the TXR Lisp interactive listener of TXR 185.
Quit with :quit or Ctrl-D on empty line. Ctrl-X ? for cheatsheet.
1> (set a.b 3)
** warning: (expr-1:1) qref: symbol b isn't the name of a struct slot
** warning: (expr-1:1) unbound variable a
** (expr-1:1) unbound variable a
** during evaluation of form (slotset a 'b 3)
** ... an expansion of (set a.b 3)
** which is located at expr-1:1
Both warnings are static. If we put that into a function body and put that function into a file, and then load the file, we get the warnings.The diagnostics after the warnings are then from evaluation.
Those are nothing; TXR Lisp will get better diagnostics over time. I'm just starting the background work for a compiler.
There is dynamic and then there is crap dynamic.
Don't confuse the two.
There is crap static too. Shall we use C as the strawman examples of static? Hey look, two argument function called with three arguments; and there's a buffer overrun ...
I mean, we can argue the semantics of what, exactly "static type checker" means, but...
A "static language" occurs when we have a model of program execution that involves erasing all of the type info before run-time. Or most of it. (Some static languages support OOP, and so stuff some minimal type info into objects for dispatch.)
Note how above, my expression executes anyway; the checks produce only warnings. The warning for the lack of a binding for the a variable is confirmed upon execution; the non-existence of the slot isn't since evaluation doesn't get that far.
If we retain the type info, we have dynamic typing. There is no limit to how much checking we can do in a dynamic setting. The checking can be incomplete, and it can be placed in an advisory role: we are informed about interesting facts that we can act on if we want, yet we can run the program anyway as-is.
For example, these days it's quite possible to ask GHC to defer type errors to runtime. Does that mean that the GHC dialect of Haskell is dynamically typed? This is basically a command line switch away, btw.
Retention of type information does not "dynamic typing" make. As a trivial example, consider C++ RTTI.
You really have just reinvented static (type) checking and a good runtime. There's no shame in that, but let's not pretend that these are opposing forces.
I still think you're just arguing semantics.
EDIT: Incidentally, the statically typed crowd can even go the "other way", namely from runtime -> compile time. For example, it's quite possible to derive a static proof/type from a runtime value in e.g. Idris by pattern matching as long as you're meticulous about building up the proof.
Excellent. My point exactly. I have no fear of using a static or dynamic language, as long as it is a good implementation of a statically (or dynamically) typed language.
Good "dynamics": All the Lisp-family languages. Smalltalk. Julia. Lua. Tcl.
nothing stops you from using static typing with python3
The typing spec provides for supplementary "stub files" that can be provided for third-party dependencies without their own annotations. The typeshed project provides these for a fair and quickly increasing number of common dependencies, and is plugged into pycharm and mypy by default: https://github.com/python/typeshed
Can we stop pretending that adding type annotations to a 'dynamic' language solves the "good static typing" problem? It's just silly.
(About as silly as pretending that static types solve all problems.)
Usually I use normal keywords for throwaway or glue code, but anything important (my actual domain entities) will be namespaced, allowing (relatively) pain free refactoring.
Cursive has a few good refactoring tools/shortcuts, but I would also like to see extract/inline/move for functions.
Its not a huge problem, just something I miss from the static languages.
Not just, "who the hell uses this", but "where the hell is this defined" as well.
On Common Lisp, a dynamic language, I can also get this answered instantly. I just press a key combination on a method call and i jump to the definition.
So this isn't exclusive to statically typed languages.
Maybe good tools are able to perform some static analysis and rule out some of the methods with the same name but impossible types, but the language doesn't rule out situations where the best the tool will be able to do is show you all of the function definitions with the same name as the (dynamically dispatched) function call site you're looking at.
Let's say you have seven different type hierarchies having dynamically dispatched functions named "run", with 5 definitions in each hierarchy, for a total of 35 functions named "run". In a statically typed language, if the code compiles, it's possible to narrow down the type for a given call site to either one of the hierarchies or one definition, meaning you have to look at either 1 or 5 definitions. In a dynamically typed language, there are situations where legal code results in the tool having to throw up its hands and show you all 35 definitions.
The flip side is that if you really have a spot where you'll need to dispatch to any of the different hierarchies, then in a strong statically typed language, you'll need to either create an algebraic sum type covering all 7 hierarchies, or you'll need something like a typecase / typeswitch statement to enumerate out your possibilities.
And even in a statically-typed language there will be cases where the tooling can only determine fairly generic things statically.
I don't see anyone advocating for abandoning static typing over that occasional limitation. Yet I do see people proposing similarly-infrequent issues as cause to abandon dynamic typing.
When $problem happens in $language_I_dislike, it's a clear sign that the language itself is inherently broken.
And that's really all I care about, I'm not about to start writing production code in Lisp.
Well, usually. It gets a little confused when you start using dependency injection containers, or dynamic requires, or anything like that.
How can it be a niche language, if it's an ANSI standard, has more than 8 or 10 fully feature, standard-conformant implementations, runs on most CPU types, and has been proven to work in production systems for spaceship guiding, worldwide airfare reservation and credit card transaction verification?
You use Js and Python because you choose to use it, but it's not the only choice. Not only Common Lisp, you could also be working in Clojure with many benefits.
It is not. A language feature is either amenable to static analysis (not necessarily type checking) or it is not.
> Consider dynamic class loading in Java, dlopen / reinterpret_cast in C++ etc.
This actually emphasizes my point. Features that are not amenable to static analysis are problematic for tooling.
The 99% stat is quite likely a big exaggeration.
Refactoring is far far harder to do reliably, and more straining as so much more responsibility on the programmer.
And the other way around: Statically typed languages without module systems, such as C, exhibit this problem too.
You would think by looking at the code that the creators had a 30 word vocabulary, because 80% of the code uses the same six nouns and four verbs to pass data around and what you use those for depends on the context of who is calling it.
Oh, but the entire thing is written using promises, so most of your function calls have no context. It's hell, and I'm starting to worry that Node has dug itself a reputation hole it will never get out of.
Nobody ever talks about that little horror when they bring up how Smalltalk could to refactoring JUST FINE without static types. It wasn't just fine, turns out.
In smalltalk the parameter names are part of the function name to reduce the likelyhood of name clashes. You still have the same problem when you have two functions with the same name and parameters.
I think the best thing I've found for this personally is coccigrep, which works but I've only used it a couple of times. I'd like something I'd reach for about as often as I reach for grep. (Also I think these days you'd want it to be based on clang or something.)
One thing that does seem to be true is that the requirement to name types means that a textual grep is way more reliable than it is in C. If I want to find all places where a Python class is used in a large codebase, I might as well give up.
Also they are backed by Clang and muuuuuuuuuuuch faster than in Visual Studio + whatever paid extension
A very nice feature it has and that I didn't see elsewhere is the optional case-sensitive renaming. eg renaming Foo to Bar will also change foo to bar and FoO to BaR.
People were complaining about static typing for the dumbest reasons (it's too 'wordy'). It started as a backlash against old-school enterprise Java development (which was fair, EJB2 world sucked) but then it went completely off-the-rails. Typing in Java could be better, sure, but even with its quirks it's way better than the nothing you get with dynamic languages. There are a class of bugs you just never need to worry about when the compiler does some compile-time checks for you ... like worrying that you passed the wrong type into a function, or the wrong number of arguments.
Thank God people are coming to their senses.
In my experience, the cost of static typing feels roughly constant per line of code, while the benefits of static typing feel roughly O(N log N) in lines of code or O(N) in number of cross-type interactions. These are just wild guesses based on gut feelings, but they feel about right. The constant factors are affected by individual coder preference, experience, and ability, but also specifics of thy type systems involved and the strength of type inference in the tools being used.
In any case, I think often times dynamic typing proponents and static typing proponents have vastly different notions of what a large code base is, or at least the size code bases they typically use.
One problem is that many code bases start out where the advantages of static typing aren't readily apparent, but re-factoring into a statically typed language is often not realistic, even/especially when a project starts groaning under its own weight.
I'd love to see more mainstream use of gradual typing/optional typing/hybrid typing languages, especially something like a statically typed compiled subset of a dynamically typed interpreted language, where people could re-factor portions of their quick-and-dirty prototypes into nice statically typed libraries.
I disagree; that Java was the standard example of statically typed languages is what convinced me for a long time that I didn't want anything to do with it. Having to pollute my code with all that crap, deal with a lot of dumb restrictions and still have NPEs left me with a sour taste.
Only after I discovered Haskell (and more recently Idris), did I realize that static typing can actually be worthwhile.
This allows you implement patterns like duck typing which are idiomatic in languages like javascript, but impossible to implement in java.
In fact, the only cases I've ever swapped even a HashMap has been to trove, which implements data structures for builtin types rather than reference types. In which case using interfaces everywhere doesn't help.
What crap? Types?
>deal with a lot of dumb restrictions
Like what?
Types, especially those that could easily be inferred and that provide no value to the programmer. Writing types down can be useful - Python programmers do it too. Having to tell the compiler every little thing is crap.
Like what?
Type erasure. Having to treat primitives and arrays differently from other types. No first class functions or classes. I won't go on, the arguments are easy to find.
I am surprised though that you were completely ignorant of the benefits of static typing outside of Java. I would think that simply out of curiosity you would do a language survey just to get an idea of what else is out there.
Persuading you on the general demerits of Java wasn't really my intention; my point was that if you want get more people on the static typing train, Java is a bad ambassador and might work against you.
I am surprised though that you were completely ignorant of the benefits of static typing outside of Java. I would think that simply out of curiosity you would do a language survey just to get an idea of what else is out there.
Well, back then (early 2000s) I was a self-taught teenager with a poorer grasp of English (I'm not a native speaker), so while my curiosity did lead me to discover a few languages (JavaScript, PHP, Python, Lua and C), anything remotely approaching "academic" - Haskell, OCaml, Oberon, etc - was out of bounds for me.
Since C was the only other statically-typed language I knew, and I also knew it was much older and designed for much slower machines, I assume static typing was mostly for efficiency, like manual memory management.
There are no senses to come to. Static and dynamic typing each have their own benefits, and there are genuine tradeoffs to choosing one over the other. That we are even having this debate in 2017 shows that the world of typing is not a "solved problem" and there are still good reasons to use one over the other for various reasons.
I struggle to think of any benefits of dynamic typing on a reasonably sized code-base (e.g. 50k+ LOC).
There's always going to be an agility multiplier so long as VC is flowing and getting an mvp and a high head count is worth more than any kind of sustainable product.
I expect any programmer to be able to transfer their skillet to a new programming language - especially when we're talking about mainstream languages with a GC.
>There's always going to be an agility multiplier so long as VC is flowing and getting an mvp and a high head count is worth more than any kind of sustainable product.
What kind of agility multiplier? Maybe it makes a difference during a hackathon where you have 24 hours to put something together or maybe if you're putting together shell scripts ... but taking something to MVP takes weeks or months - mainstream dynamic languages simply don't have any edge in development speed in those instances.
Being able to define and initialize types at runtime offers more flexibility and it's quicker to develop in.
I'm frankly surprised nobody brings it up more often but the prototypical example of "static typing done right" - Haskell - is talked about nearly constantly but when I look for actual software I might use that's written using it.... there's so little it's almost embarrassing. One obscure window manager, one obscure VCS, facebook's spam filter and some tool for converting markup.
Given a sprinkling of asserts, a decent linter and a high level of test coverage I don't see much of a benefit to adding static typing.
Quicker if you're writing shell scripts or a small single-purpose applications. Not quicker if you're adding to a codebase of any significant size.
Yes, IME it's still quicker.
OTOH, if you're using "codebase of significant size" as code for "big ball of mud", static typing certainly helps, but integration tests are the real lifesaver.
No. I mean when the codebase is of a certain size, new features require some thought and planning. Features may span multiple-modules. They may require partial or full rewrites or the refactoring of any number of sub-components to support the new behaviour. This means that you proceed carefully because you may not want to introduce regression bugs. This costs time. At that point, you're not limited by your typing speed as you may be putting in net 10 lines of code a day. There is just no benefit to dynamic typing at that point. Worse for dynamic languages, this is where improved tooling and static type constraints start paying extreme dividends.
Yes. And all equally true for statically typed languages.
Refactoring without tests is easier in a statically typed language, but still stupid. If you assume a decent body of tests, the benefit dissipates quickly.
If you prototype faster, as you usually will in a dynamically typed language, your design mistakes cost less. Since in large software systems I tend to find that the two biggest sources of bugs are a) errors in specification and b) poorly designed APIs, not obscure edge case bugs, quicker prototyping helps in large projects too.
And, if your design is solid, you can still achieve similar benefits as static typing by "locking down" your boundary code with asserts so that future development that interacts with that boundary code will fail quickly if it interacted with in the wrong way.
>At that point, you're not limited by your typing speed as you may be putting in net 10 lines of code a day. There is just no benefit to dynamic typing at that point.
This is fallacious. You're never limited by your typing speed in any language at any point. The cost of "extra typing" is cognitive, not a finger speed limitation.
The benefit of dynamic typing is more flexibility in the code you write (especially useful for writing frameworks and such) and quicker turnaround when prototyping because you do not have to prespecify as much up front.
>Refactoring without tests is easier in a statically typed language, but still stupid. If you assume a decent body of tests, the benefit dissipates quickly.
We're not arguing whether dynamic language+extensive integration/unit test is better than static typing and no tests.
>And, if your design is solid ...
Yes, if you have a very solid architecture, strict coding guidelines, extensive integration and unit test coverage, experienced developers (etc. etc. etc.) you will mitigate a lot of problems with dynamic typing. So if you do everything right, avoid the pitfalls, you can have something solid. A similar argument is made to me when I assert JavaScript is a terrible language. I don't disagree with either but it doesn't prove anything.
>The cost of "extra typing" is cognitive, not a finger speed limitation.
Exactly.
I am, because that's the way I'd work in any language, because I'm not a hack.
>Yes, if you have a very solid architecture, strict coding guidelines, extensive integration and unit test coverage, experienced developers (etc. etc. etc.) you will mitigate a lot of problems with dynamic typing.
Eliminate.
>A similar argument is made to me when I assert JavaScript is a terrible language.
No, javascript is different. The weird and fucked up implicit type conversions render even a high level of testing insufficient to achieve a high level of confidence in the code. There's way too many edge case behaviors where it should be throwing exceptions and it does something weird instead. C suffers from this problem too despite being statically typed.
And yet, it's done all the time with great results.
There is a different problem with the more powerful and useful type systems in more modern statically typed languages though: learning curve. Haskell is dysfunctionally hard to learn and other languages do a little bit better but there's still friction in the learning curve that gets in the way of widespread adoption in projects that want to be able to hire rapidly.
This is the #1 reason I leaned away from static typing. Typescript and Swift have changed my mind. I now see typing as a helpful tool that can solve a lot of problems.
People always say this and it baffles me. Bugs like that should be caught immediately by your test cases. You shouldn't rely on the compiler to catch them for you.
I worked on a small Python project some years ago and we had a type error in production despite having tests.
We traced it back to a call to a third party library. It was supposed to return a list of results, and all of the test cases around it worked and always got a list back. In production however we encountered an error because if there was only one value to return, the library would not return a list of one element, as we expected, but a scalar value. So the rest of the code was expecting a list and when it encountered a scalar it blew up.
You can blame it on us for having insufficient test cases, or not coding defensively enough, or not reading the source code of the library we used, or the author of the library for bad design, but ultimately, this bug would not have been possible in a statically typed language.
So just saying "have test cases" is not good enough. Your test cases can be not exhaustive, but a good static type system and type checker is.
That's the whole point: as it's often said "type checking keeps you honest"
I stumbled time and time again upon badly designed libraries... With a static type system, the painfulness will be obvious and felt the first time you'll try to build your code
with dynamic types, the pain might not be felt at all, until a crazy bit of code will be invoked, sometimes at the most unfortunate of times
That's the one. That's a damned stupid decision.
By adding sanity checking asserts in a dynamically typed language you can achieve more or less the same result.
Yes. We call that 'typing'.
I see all too often, java bad, just look at how many lines you need to write to get "hello world". Who cares, the IDE generates that for you, but if you don't understand static void main as a beginner... again who cares, just put it in and ignore it until you need to understand it. Also read that dynamic languages are so productive, but they never mention you need to then write tests to detect what the compiler would catch for free. Yes good code needs tests, but the compiler IMO is a damn good built in test suite for catching many classes of errors
What's wrong with relying on the compiler? Bugs like that will be caught immediately by a good static type system, so you don't have to rely on your test cases to catch them for you.
Relying on a test suite to verify basic properties that could be enforced automatically through a type system means you're only checking some cases instead of all cases. It also means you're cluttering your test suite with boilerplate about language mechanics instead of writing high value tests that verify the real operational behaviour of your system.
There are pros and cons to static vs. dynamic typing in general, but in this particular respect, static typing is strictly more powerful, less verbose and more efficient.
None of those things are true.
In general though, the more you can formally reason about the program, the more you can automate program transformations (refactoring). Programmers in dynamic languages will argue that the amount of code is far less than the equivalent code in a mainstream statically-typed language, so while the cost of refactoring may be higher per unit, the number of units is less, so the overall cost is the same (or less).
I believe in using the best tool for the job...some use cases would benefit more from static typing, while others would benefit more from using a dynamic language. One of the most important factors is the team and its engineers' backgrounds, preferences, styles, etc.
...but there's plenty of sales charlatans out there who will say "I intend to get the manager of that IT dept to make its developers use my tool for the job, and I don't care if my tool is the right one or the wrong one."
Yes. PHP developers.
:)
The realization that with types, smart enough compiler can implement interfaces for me, was amazing.
Unfortunately, I am afraid that it will take a while for these techniques to go mainstream. A.f.a.i.k most a mainstream language can do, is to fill in the method stubs for you.
There are no diminishing returns. Defining types is easy and enhances code readability.
Getting a language to the point where it's workable for serious projects is a lot of work. Rust is getting there with the backing of Mozilla, Haskell has made some decent strides too (but still has a way to go, and I think has some pretty fundamental flaws entirely apart from the type system). It'll be probably another decade at least before we see any dependently-typed languages getting a serious foothold, but I do think they're going to become a lot more common eventually.
IMO, machine assistance is useful to the extent it relieves us humans from work. In particular, types are useful to the extent they can be inferred. Beyond that, you still need to prove the correctness of your programs on your own, so there is no point to the ceremony of writing down those proofs in a machine-checkable format.
It's also self-evidently wrong. Agda was first released in 1999, ten years before Go. If you use a wallclock interpretation of "maturity", Agda is twice as old as Go and Idris is roughly as old as Go. Both are used significantly less (by several orders of magnitude), though. Despite them having a far stronger type-system.
If you, on the other hand, you are using a "developers' time" interpretation of maturity, on the other hand, you are making a circular argument, i.e. "Agda is seeing less use, because it has been used less", as resources invested in a language ecosystem tend to be strongly correlated with it's usage.
Essentially the types being used as so complex the type checker cannot automate the decision about two types being compatible so you have to write maths proofs to help. The types used in mainstream languages are simple enough that the type checker never needs help like that.
The cost of formal verification right now is immense but the benefit is close to bug free code. Mainstream strong statically languages require nowhere near the same amount of effort and give clear benefits over dynamic types.
I don't think they enhance code readability - I think they make it worse. I never look at the type when I am reading code, it just gets in the way.
You can pretty much use any language in that scenario. But the chickens come to roost around day 30+ or so.
Meanwhile real-world non-trivial projects tend to be large projects.
Nice to be prepared for that instead of gambling on "surely we'll extract out smaller projects that fall on the right abstraction boundaries in the face of unknown future requirements."
How big are the "real-world codebases" you're talking about, and how many programmers are working on the code? Once you hit 5-10 million lines of code and/or thousands of developers, static typing really helps manage complexity.
Well that's provably false, because there exist properties that you can type check that literally can't be verified via unit tests, even in principle. For instance, race and deadlock freedom.
Are you kidding? Python programming's my day job but Haskell is an order of magnitude easier to refactor.
Large Python code bases are really hard to understand and work in (here).
Of course there are cases where dynamic languages do worse, but it balances out I think.
Unless you think original means Bill Opdyke's thesis work, where the tooling was written for C++ and written in CLOS.
C# has a very weak version of this with the auto keyword. Languages like Crystal take it much further by tracing the flow of data through the entire program. It generally works quite well, though there are a few edgecases that require explicit type annotations.
As for auto-completion, some languages feature designs that make it easy to offer auto completion even without type information. For instance, Elixir doesn’t have methods. You only have functions defined on modules, and it’s trivially easy to know what functions are defined on a module.
So it’s possible, but there are some limitations.
> C# .... Crystal
Both are fully statically typed languages with type inference. Those are unrelated to the argument the parent comment is making.
That would imply there's no type inference possible with dynamic languages - either at "compile" time or run time.
(Wouldn't it also imply that static typing and strong typing are synonymous?)
I can and have built a totally untyped language within a fully statically typed language - nostrademons' Scheme-in-haskell exercise is a lot of fun.
You just have to define a Universal type and then back out of all that nasty compile-time nonsense. Everything is Univ and Univ is everything.
fn foo<T: Positioned>(x: &T) -> Point {
x.position()
}
Note that this doesn't work in languages that use templates for generics, like C++, where templates work more like compile-time duck typing.For OO languages and methods it does get a little guesswork-y, and tools often offer a wider range of guesses than is correct for completion. But you can show the class along with the offered completion, so it's not too bad.
Yes, you can find all references to a method in Smalltalk -- but those references are not separated-out from all the references to other methods that happen to have the same method name but are defined on a different class.
With type information for the receiver and method arguments, we can find just the references we're looking for.
Automated refactoring was invented in Smalltalk, claiming it's a benefit only static typing provides is to not know history.
History: In Bill Opdyke's thesis work, the tooling was written for C++ and written in CLOS.
Incidentally, what's your source for "Ralph Johnson… was the creator of the first Smalltalk refactoring browser" ?
We still don't know if you simply confabulated your other claim.
I always thought dynamic typing is a feature for situations where the code needs an extreme amount of flexibility to adapt to a wide variety of data; even at the expense of performance.
Not necessarily. The phrase "dynamic language" actually bundles together a lot of related but distinct ideas: some of those add performance overhead, others don't. "Dynamic" features which are most notable for performance overhead are tagged unions and dynamic dispatch.
Imagine a dynamically typed language which provides types like int, bool, list, functions, etc. and we're free to assign (and reassign) any of those values to any variable we like:
x = 5 # An int
y = true # A bool
y = 3 # An int
z = square(x + y) # An int
It's very common to store such values as a tagged union: a "union" meaning that the data could represent an int, or a bool, or whatever, and "tagged" meaning that there's some extra data which tells us which one it is. For example, we might store `5` as a pair of machine words: `1` to indicate that it's an int, and `5` to represent the data. The boolean `true` might be the pair `2` to indicate bool and `1` for the data. And so on.This tagging adds overhead. We can reduce it in some cases, e.g. using "tagged pointers" where we use some of the bits in a word for the tag and some for the data. But it's still overhead.
However, there's nothing fundamental about using tagged unions. We could just as easily use 'unboxed' values, i.e. store the int `5` as the machine word `5`; the bool `true` as the machine word `1`; etc. There is no overhead, no metadata, etc. Whilst this is a perfectly reasonable implementation strategy, it means that we cannot tell what type a value is intended to have: e.g. if a value is stored as the machine word `1`, we have no way of knowing if that's the boolean `true`, or the integer `1`, or the character `SOH`, or whatever. This would probably lead to very buggy programs, since we have no type checker to enforce correct usage, and (since there's literally no difference between data of different types) we can't even do runtime assertions like `assert(isInt(x))`.
Likewise, many dynamic languages use dynamic dispatch to choose which functions to call based on the type of data we have. In the above example, we might have `x + y` running an integer addition function when `x` and `y` are integers, or a string concatenation function when `x` and `y` are strings, and so on. That's what Python and Javascript both do. Yet, again, there is no fundamental reason to do this! We can have a dynamic language which uses static dispath everywhere: consider that in PHP, `+` is only used for numerical addition, whilst `.` is only used for string concatenation. Dynamic dispatch adds overhead, since we need to chase pointers, etc. whilst static dispatch doesn't. This is simply a question of programmer convenience: do we want every function to have a distinct name, and write them out in full each time?
Note that both of these features: tagged unions and dynamic dispatch, can be used in static languages too. It's just that, historically, they tend to be default (and hence unavoidable) in dynamic languages, and something we must explicitly create in static languages. Hence when we compare static languages to dynamic ones, we tend to compare statements like `x + y` in Python to `x + y` in C, which are actually quite different semantically. A fairer comparison would be to compare `x + y` in Python with `callWith(lookUpSymbolFromType("+", lookUpType(x)), x, y)` in C (I've made up those function names, but the point is that the same functionality is there if we want it, but it will be just as slow as if we'd used Python)
I didn't say so. An essential feature of type systems is being able to determine the types of (many) values, statically or dynamically.
> You can not deference a floating point register as an address, for instance.
So you'd agree that architectures that don't make a distinction between integer and floating point registers are untyped? But sure, call this a type system if you must. It's just a very very weak one, so weak as to be almost entirely useless. (And the reason floating point registers are often separate from integer registers is not to provide this kind of "type safety", it's due to history and architecture.)
Weak and strong aren't meaningful terms. A machine ISA might have an inexpressive type system and/or an unsound type system (because it conflates addresses and integers).
> And the reason floating point registers are often separate from integer registers is not to provide this kind of "type safety", it's due to history and architecture.
No, the reason is performance. And we get performance by making statically known distinctions between datatypes, which is what the original poster asked about.
Intermingling the integer and floating point circuitry so they access the same register file would never improve performance over keeping them separate. You'd need longer wires to place them both near the same register files to minimize signal latency, an the added signal delay alone ensures lower performance.
> No, it's for architectural reasons.
You win, I guess?
Perhaps I should have written "... nontrivially statically typed."
And there are all sorts of optimizations like this that simply aren't available to dynamically typed languages. Tracing JIT can only take you so far.
(There are also all sorts of optimizations that can't be done statically, so I guess there's that.)
I still don't think so. For example, plenty of silicon is spent on branch predictors simply because addresses and integers aren't distinguished, in general, thus permitting more expressive but costlier code.
Execution would be much faster if integers and addresses were forced to be distinct. Static typing pretty much always improves performance.
This isn't to say that static typing isn't good at this. Just, even with that, there is a lot of effort that goes into making the rich tooling. A lot of very smart and capable folks work hard to make Visual Studio.
vscode seems to figure out the types in javascript without any static typing.
>But it is great for refactoring
Searching for strings isn't that much worse. Also, when it comes to web development, you cross into the client-side and suddenly you can't refactor. So you can only refactor the server-side and end up with a mismatch.
>finding all references to a function or a property or navigating through the code at design time
You can do that without static typing in many cases as well.
>Basically all the features visual studio excels at for .net languages.
When I was working in c# on the server and javascript on the client, I really hated having to go back into c#.
>telling you through a drop down what other options are available from there
vscode seems to be able to figure this out most of the time as well.
I think static typing is necessary when you need performance because all of the fast languages are statically typed.
I think a lot of these things are about organisational complexity and making sure new and average programmers don't screw up the software. It is about large companies trying to manage their organisation, it isn't about the complexity of the code itself.
There are a ridiculous amount of tech companies that have used dynamic languages to go from nothing to the biggest companies in the world and only switched to static languages well and truly after that occurred.
It is actually using TypeScript's engine for this. It uses TypeScript's type definitions where it is available (e.g. most popular libraries and built-ins), and some inference rules where it has to work with plain JavaScript.
While this does give you decent auto-complete in a lot of cases (and still getting better), it's not quite as good as using TypeScript directly.
> Searching for strings isn't that much worse.
I'm busy with a large refactoring project, and TypeScript has been amazing for this. After restructuring code, you can just keep on fixing things until there's no more red. This is not just about reducing bugs - it removes almost any thinking/mental overhead required for the refactoring process.
> Also, when it comes to web development, you cross into the client-side and suddenly you can't refactor. So you can only refactor the server-side and end up with a mismatch.
TypeScript also works very well for client-side. Of course, if you change the API between the client and server, that's a different story.
There are limits to type inference. And if you're going to rely on type inference to prevent runtime bugs you might as well double-down on static typing since you're giving up on some of the 'features' (insanity) of dynamic languages anyway.
Dart 2.0 now mandates strict typing but will allow you syntactic shortcuts as long as the compiler can infer the type (if it can't, you get a compile-time error) - that's a great compromise. I wish more people would love Dart. It's such a great, well-designed, language.
>Searching for strings isn't that much worse.
There are very real limits with what you can do with 'strings'. And yes, it is that much worse.
>When I was working in c# on the server and javascript on the client, I really hated having to go back into c#.
I do not understand that view. You are an alien to me. C# is a beautiful language that fixes a lot of syntactic problems in Java. It is much more pleasurable to write C# code than JS code (outside of dinky 50 line programs).
>I think static typing is necessary when you need performance because all of the fast languages are statically typed.
That's not the only reason but it is one of them. JIT and AOT compilers can do more with strongly typed code.
>There are a ridiculous amount of tech companies that have used dynamic languages to go from nothing to the biggest companies in the world and only switched to static languages well and truly after that occurred.
Sure. PHP (pre-5) and JavaScript made a ton of money for a ton of people. Both languages were integral in the Web revolution. Doesn't change the fact that PHP was a terrible language and JavaScript is still a terrible language.
The unknowable question is, would they have hit that sweet spot anyways by engineering their product more rigorously, and had less pain later? Or would it have impeded them in the exploratory phase of writing and rewriting their code until they hit that spot?
Doesn't it do this by treating Javascript as a statically-typed language (Typescript) and using type inference?
https://github.com/Microsoft/TypeScript/wiki/JavaScript-Lang...
> Visual Studio 2017 provides a powerful JavaScript editing experience right out of the box. Powered by a TypeScript based language service, Visual Studio delivers richer IntelliSense, support for modern JavaScript features, and improved productivity features such as Go to Definition, refactoring, and more.
It works off Typescript type annotations for packages and the Typescript compiler's type inference. VS Code's Javascript editing does not seem to be evidence for tooling around dynamic languages so much as it's evidence that if you have a lot of money and Anders Hejlsberg you can write a compiler for a statically typed language with type inference that looks like a specific dynamic language.
Are there not definitions written by someone or a tool that vscode looks at?
That is what I saw using some npm packages with typescript: http://definitelytyped.org/
This is a biased sample though. You're saying 'ridiculous number', but the truth is most startups (using static or dynamic languages) fail and we don't actually know if their language choice had much impact on their success or failure.
As you might've noticed, I have been intentionally light on the details and only talked pretty abstractly about the specific scales and factors involved.
I use Cursive https://cursive-ide.com/ for working with Clojure, and it can do safe refactoring for symbols by doing static analysis of the source. It can show all usages of a symbol, rename it, do automatic imports, and so on.
Another piece of tooling that's not available in any statically typed languages at the moment is REPL integration with the editor seen here http://vvvvalvalval.github.io/posts/what-makes-a-good-repl.h...
I find that the REPL driven workflow found in Lisps is simply unmatched. When you have tight integration between the editor and the application runtime, you can run any code you write within the context of the application immediately. This means that you never have to keep a lot of context in your head when you're working with the application. You always know what the code is doing because you can always run and inspect it.
Having the runtime available during development gives you feedback much faster than the compile/run cycle. I write a function, and I can run it immediately within the context of my application. I can see exactly what it's doing and why.
The main cost of static typing is that it restricts the ways you can express yourself. You're limited to the set of statements that can be verified by the type checker. This is necessarily a subset of all valid statements you could make in a dynamic language.
Finally, dynamic languages use different approaches to provide specification that have different trade offs from static typing. For example, Clojure has Spec that's used to provide runtime contracts. Just like static typing, Spec provides a specification for what the function should be doing, and it can be used to help guide the solution as seen here https://www.anthony-galea.com/blog/post/hello-parking-garage...
Spec also allows trivially specifying properties that are either difficult or impossible to encode using most type systems. Consider the sort function as an example. The constraints I care about are the following: I want to know that the elements are in their sorted order, and that the same elements that were passed in as arguments are returned as the result.
Typing it to demonstrate semantic correctness is impossible using most type systems. However, I can trivially do a runtime verification for it using Spec:
(s/def ::sortable (s/coll-of number?))
(s/def ::sorted #(or (empty? %) (apply <= %)))
(s/fdef mysort
:args (s/cat :s ::sortable)
:ret ::sorted
:fn (fn [{:keys [args ret]}]
(and (= (count ret)
(-> args :s count))
(empty?
(difference
(-> args :s set)
(set ret))))))
The above code ensures that the function is doing exactly what was intended and provides me with a useful specification. Just like types I can use Spec to derive the solution, but unlike types I don't have to fight with it when I'm still not sure what the shape of the solution is going to be.I can encode all those invariants as QuickCheck properties and have them automatically tested against random inputs on every test run. It's still all runtime verification, but with random inputs I actually have more confidence of hitting a corner case than with just asserting during regular program runs or hand written example tests.
Also, with enough heavy lifting you can actually encode all of that in the types in a dependantly typed language like Idris [1]. And while a machine checked proof of your sorting algorithm is nice, it might be hitting the diminishing returns point the article mentions over just using property tests.
This makes it much more likely to be used but it's fundamentally the same set of ideas.
A really cool idea I'm playing with at the moment is using fuzzing/static analysis based generators to feed spec/test.check.
I think it will help get past the, imo, biggest issue with generators in that they can miss exceptional cases in the code.
E.g. If (x=="jack and Jill) {exceptional case} is unlikely to be triggered with standard generators but "easy" for static analysis tools to solve.
> Also, with enough heavy lifting you can actually encode all of that in the types in a dependantly typed language like Idris [1]
In theory. In practice it is multiple orders of magnitude harder to prove properties in Idris than it is to spec them using property based testing.
Somebody has to be able to read that specification and understand that it's correct in a semantic sense. Ultimately, the specification itself becomes a full blown program that the type checker executes. So, now you run a program to try and verify aspects of your original program, but how do you verify that the specification itself is correct?
At some point a human has to be able to read the code and decide that it matches the intent. This step can't be automated, and I certainly don't think the Idris example improves things. I'd argue that it's far easier to tell that this version is correct:
fun insertionSort(arr, int n)
{
var i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
And I disagree with the barrier to entry argument. Static typing, by enabling rich tooling, helps a beginner (like it helped me) a lot more by giving live feedback on your code, telling you immediately where you have a problem and why, telling you through a drop down what other options are available from there, etc. Basically makes the language way more self-discoverable than having to RTFM to figure out what you can do on a class.