Suppose I've mostly used untyped programming languages and don't have a great appreciation for types.
Let's do some convincing!
Suppose I've mostly used untyped programming languages and don't have a great appreciation for types.
Let's do some convincing!
For further actions, you may consider blocking this person and/or reporting abuse
With types, you can make illegal states unrepresentable. Instead of storing a bunch of strings, you can store a
Name
and andAddress
, and can encode into the type system thatContactInfo
must contain a phone number, an email address, or both but not nothing. By encoding that requirement into the type system, it becomes impossible to represent an incomplete record in your program. It also aids refactoring - if your business logic changes, your compiler will guide you through the refactor for ensuring your whole codebase reflects the change.I agree with this. I recently tried out ReasonML and it's awesome! Nevermind less rope to hang yourself with, it really gives you no rope! I'm still trying to learn more about it though, like about phantom types and some clever ways to use types to enforce structure and rules in your code without using a single conditional statement.
One of the best advantages of types is that it lets you catch errors before the code is executed. With the right precompiler/language server, you can see that your code is faulty even in your IDE. I can only speak for Javascript to give you an example.
It is a
sum
function that takes in two numbers as the arguments. However, a common mistake is to think that thesum
function can take in multiple arguments then get a sum of them. Maybe the function is imported into a different file and you might have already forgotten about the interface.Unfortunately, you wouldn't know that you're making a mistake until you run the code in the browser and test the feature that is using the code, or you have your unit tests running. The scariest part is, in the browser, it won't even throw an error.
With Typescript, you can spot this in your IDE even before it is run anywhere else. This is how it looks like, more or less:
This is just a really simple example. Of course, the mistake is obvious on this one, but, as the software gets more complicated, the argument for the necessity of typing (IMO) is going to get more and more valid. For more info on this topic (Typescript), I've written an article about this (shameless plug 😋):
How strict is Typescript's strict mode?
briwa ・ Jun 1 '19 ・ 7 min read
Another advantage that I find it useful is the documentation. With a good IDE integration, Typescript (or any strongly-typed language) code is sort of self-documented, but if you want to take it up a notch, you can easily generate a user-facing documentation from it without a hassle, using libraries like Typedoc. It would help a lot for, say, you're creating a library in Typescript and you want to put up a page for the API documentation.
But I also understand the other side of the story. I've read this article, and I can see that the overhead of using Typescript (or any strong-typed language, for that matter) can be too expensive to some. I would say, if you still want to skip typings, at least have a good documentation and a good testing coverage. Without these two (and also typings), I'm not sure if maintaining the code would still be productive when the code is growing in complexity and also the number of devs maintaining it ;) Just my two cents.
How about user input? you define as a number but user inputted string? you catch the error or the compiler throw the error?
If you're talking about Typescript, it won't catch them, because in my opinion Typescript is not meant to be used to define user interfaces and user inputs (unless you're talking about
.tsx
files, but it's going to get too specific, which is out of topic). In general, side effects I/O such as user inputs should be validated/specified by an end-to-end test.In HTML, you can definitely set a "type" to your inputs (for example
<input type="number" />
for number-only inputs). But again, the context matters. If you have a use case and you have your own set of expectations of what a strongly-typed language should do, maybe I can understand your problem better.EDIT: @stojakovic99 answer is more apt, I guess it's better for me to say that strongly-typed languages help you to define/catch errors before runtime, and outside of that (like user inputs) it should be handled differently (maybe an e2e test).
User input is done during the runtime, so, you need additional measures to catch the error. Personally, for TypeScript I use class-validator and treat whole API request as DTO. For Java I use bean validation.
Yes, that's it, I use typescript before I do what you do too, this is why I'm still not using it (Unless I use Angular). if I want to sell TS to somebody else definitely not the typing system. the IDE and OOP make the refactoring code better, autocomplete, what else, typing system doesn't make less bug and maintaining code better.
Just use this, basarat.gitbooks.io/typescript/doc... reading this makes me use typescript for 2 months. then back again to plain javascript, some problem with another lib still sometimes occurs in TS (usually typings). I can't stand that :(
User input cannot be caught by Typescript, because user input is brought in at runtime.
You don't run Typescript, you compile it to JavaScript and run the JavaScript, so by the time it's running, type information is discarded.
However, Typescript will help you prepare a function to receive user input by setting up the appropriate types, but that's as far as it can go.
Slow down there! You already got a response from me today about
switch
. :DI can talk for days, literally days, about how awesome types are and the problems with untyped languages...
...though I figure I might not have to, in about a year, as the dev codebase grows, and the contributors increase, you'll look back at this post and cringe. ;P
Imagine you have this function
how would you test this does what you think it should do? The way this is written combine can accept any
a
orb
and can return anythingNow lets add some types
For your program to compile
a
andb
must both be of typeInt
and combine must return anInt
. This means rather than testing every possible input and output, you now only consider a tiny subset of the inputs/outputs you originally started withHere's another example. This function is parametricly polymorphic in
T
(that's what the square brackets are saying), we must take aT
and must return aT
Can you think of an implementation other than this? Remember
T
can be anything, so the implementation must work for any possibleT
I can't. And in fact the types have limited the space of implementations for this function down to just this and things like just throwing an exception or doing a side-effect.
Depending on your language you can go really far with this. In lots of FP languages OOP is never used and instead ad-hoc polymorphism (aka typeclasses) is preferred. The idea is really just an extension of the idea "my program won't even compile if the types don't work". If your language has higher kinds, you can meaningfully talk about things like IO and sequential/parallel computations. If you have a language like Idris with dependent types, you can do type-driven-development, where each time you compile your program you do a "proof of correctness" (note the quotes before you start yelling at me :) )
I enjoy writing in TypeScript for this very reason. The documentation can be garbage, but at the very least I can look at the distributed definition files for guidance.
I used to cringe at JavaScript for the lack of types because I feel unsafe, but then after years of using JavaScript, I've grown pretty comfortable with it and just know where I needed to do type checks and coercion. Now, I cringe at how slow I work with Typed languages because of the additional mental effort to think about the type of every variable and the compilation time. But really, I've just gotten really spoilt, because the extra mental effort and time waiting for compilation is not significant really.
The thing I came to realise about why I would pick Typed languages is to make it easier to work with junior developers. I used to feel unsafe with JavaScript and now I feel comfortable with it, and the reason is simply because of experience from making all sorts of mistakes before. I find myself frequently pointing out to junior devs now where they have missed a potential type error and need to add type checks and/or type coercions when working with JavaScript. At the end of the day, I think Typed Languages have better developer experience. Plus, I really rather a machine tell me that I have made a silly mistake than having wasted the time of a colleague pointing it out to me later on.
Let's clarify a bit. You may think untyped language is a language which has no types (the name suggests it), but in reality, it is a language with the single type (it doesn't make sense to talk about types if there is only one). Examples of untyped languages: untyped lambda calculus (lambdas), assembly (bit strings). Most of the languages have types. Let's take, for example, ruby (which @ben likes):
This is nothing else than type error
¯\_(ツ)_/¯
. So ruby is typed language, but there is no static type checker (at least not built in one, there is sorbet project which will be part of ruby 3).What Ben meant to ask, I guess, is how dynamically type checked languages differ from statically type checked languages.
More about terminology dev.to/stereobooster/pragmatic-typ...
First up
This is unlikely, unless you program only using bits - but that's not efficient or terribly fun. You probably mean that you've been using dynamically typed languages - which definitely have types, but do not have typed variables or a type checker to make sure that you're not, say, assigning an integer to a variable which holds strings.
It's possible that I may have written an article to address this already...
Why learn... a statically typed language?
David Wickes ・ Mar 21 ・ 10 min read
This is gonna be a really crappy persuasive argument, but I wanted to give pros and cons of types, and you can decide for yourself 😄
Pros:
myarray[0]
will never throwCons:
That's all I can think of for now. I think typed languages pay off after you get to a medium sized codebase. I usually reach for them on day 1, because I've been burned a lot by errors in dynamic languages, that typed languages don't have.
Hope this helps!
Do not ask this question to an Ada programmer: we are the hard-core of strong typing :-) :-)
Seriously, as many said, correctness is a big plus of strong typing. I say strong typing and not just typing since C, for example, is typed but not strongly (it converts silently between integer/pointers/chars/float/...). In a strongly typed instead no conversions are done by default and mixing different types by mistake is impossible.
Few years ago I wrote a program that made a .dot graph starting from Ada code, showing the dependence among packages. The code uses both package names and the names of the files that contain the package. Initially I used
String
for both of them, but I discovered that I was keeping mixing them (passing a filename when a package name was expected).The solution was very simple: I just defined
and the compiler prevented me from mixing them. A good portion of potential bugs never made beyond the compilation stage.
Of course, strong typing reduces a bit the flexibility in your code. In languages like Matlab or Rudy variable can change value type dynamically and you can call procedures with any type of parameter you want. Indeed, because of this, I find this kind of languages a good choice for short or "short lived" fast-and-dirty software: you write it in little time and it does the work you wanted. If it is short lived, you do not care about maintainability, if it is short, it is quite easy to master it anyway.
Intellisense is easier and better supported with typed languages because Intellisense knows what it's looking for. I found that I have more problems with Intellisense in JavaScript than I do in Typescript
Types catch bugs at the editor level, so even before compile time, with a good editor/IDE.
Types allow you to create functions that know what to expect. Suppose I have the following:
In the above snippit I know, and the compiler knows, that the
httpManager
, which is of type HttpManager, has asendRequest
method.But if I do the same in JavaScript:
Then neither the programmer nor the compiler knows that the
httpManager
has asendRequest
object and I could pass the function an object that doesn't have that method. Program will attempt execution and crash when it calls the function. In a typed language, this doesn't happen, because you'll catch the error at the editor level.Do you mean dynamic vs static typing? If so, I was kind of surprised recently to find that the overhead of a dynamically-typed language like Python can be quite high.
Resolving types at runtime can produce orders of magnitude more machine instructions compared to the same logic written in C, C++, or more generally, in a statically-typed language. That can easily lead to a slowdown in the 10-100x range, assuming the code is not I/O bound. I knew it was slower but I don’t think I appreciated just how much. Here's a benchmark for illustration.
My minimax code for tic-tac-toe in Python takes over a minute to run without caching (on my PC). @mortoray suggests it would be much faster in C++, even a naive implementation; possibly same as the cached version in Python, which is < 1s
This may not be relevant for every use-case but I thought it was worth mentioning.
I didn't realize this was a debate. What is 1100101110001? You have to know the type to figure it out. Is it an integer? A letter? A string? A pointer? Types are essential for doing stuff with computers.
Should you use a typed language? It depends. Are you writing short scripts? Then the overhead can be annoying. Are you writing a large application? Then the types can help ensure system integrity.
Mic drop.
To the person:
You already use types (: You don't use your chair to start your car. You don't pour water on your computer so you have something to drink. But you do use a cup for water, or perhaps a mug, or even a milk carton if you wanted. We group real-life objects like this to keep ourselves at least a little more organized in such a chaotic world.
Types are kinda like this in the programming world ^
(admittedly it's not a perfect analogy, especially because I'm a huge advocate for functional freedom, but it's a start for at least gaining an intuition)
According to Eric Elliott, a veteran programmer and Now a JS advocate,types helps for better productivity and lower bugs in his blog
The TypeScript Tax A Cost vs Benefit Analysis
Eric's thoughts on Dynamic types
I just thought you'll be convinced when some one with more experience offer their wisdom
His thoughts on types
Good one!
Had a bad experience with using Typescript on my latest npm package (because
ServiceWorkerGlobal
was very hard to use in another context than a service worker, very tough to work out in a class) and I moved to plain, untype-hinted Javascript and so far I am happy with it.For the debate on the pros/cons, I will let my peers to answer because I have not enough experience on typed programming!
I wouldn't try to convince anyone to use types. Or to avoid them, either. They're useful. But silver bullets are expensive. As I see it:
Pros:
Cons:
option
/maybe
/whatever... which raises the cost of writing codeFor some time, I saw types as a crutch for people who could not read code well enough to know what to expect in a weak-typed language like JavaScript.
That was when I still did the maintenance for most of the code I handled myself. Working in a bigger team now, I see the advantages of types: inherent documentation, catching hard-to-spot errors during compile time, easier refactoring and integration of typed external dependencies (also the tooling is rather brilliant).
One great example I heard just today on the corecursive podcast is that some typos in your JS are only caught at runtime if at all:
y
isundefined
here, you only notice this once you get a strange result somewhere or, if you're lucky, get aTypeError: y is undefined
. You basically need full test coverage to be sure this isn't happening before deploying.In a typed language like C you don't have this problem:
This will immediately give you a compiler error:
When I first started programming I thought dynamic languages were faster to program in. That was until I had a decently sized project and had no idea what the hell was going on.
User
object'sname
property tofullName
is as easy.Make the code work for you, don't work for the code!
Personally I'd prefer a compiler error in one minute versus debugging a TypeError (or worse, non-exception buggy behaviour) caused by something being undefined at runtime where it takes me 5 minutes and a series of steps to reproduce. Types really do reduce the frustration factor in JavaScript.
What recently convinced me was diving into a fairly large codebase I was completely new to, built with TypeScript.
Well-defined types mean that I can look at a function, and immediately see the shape of data it takes in and puts out. I don't have to go look at callsites to see all the data I have available in it.
Contrast that to the Elixir backend of that application. A lot of data passed around there is in maps, where I find myself looking around the code base to see which keys are being set.
As my manager described it to me last week, data types really get you to think about the members of an object.
The uses I see for types are:
Even dynamic languages have had polymorphism in the form of classes for a long time, and lisp has had typecase and now multimethods.
I think it's good that types are becoming available in dynamic languages, but I think using them will in most cases make code more verbose, and should therefore be used sparingly.
Static analysis. Automatic refactoring. Code transformations.
Types enabled the RxJS team to write code transformations that statically analyzed RxJS 5.0 code written in TypeScript and update it automatically to RxJS 6.0 code. Updating all imports, transforming older dot-chained operators to newer piped function syntax, etc. This enabled Google to update thousands and thousands of files in minutes and migrate every Google project to the latest version of RxJS easily. This would not have been possible without type information.
I should have explained better. Clojure is a dynamic language with optional typing. Also it's not an additional tool, it's baked into the language, and only possible because it's dynamic. The program is literally made from interpreting each statement instead of statically compiling everything at once.
There is also some power in not having types, or only optional types.
I really think it's a spectrum. Like in Java I sometimes miss the feature to make type aliases to make strings especially more safe. But 'cheating' with var in Java in selected places feels like a releave. And with Rust you are repeating some types a lot in some cases (but then you could use an alias). And typescript can be tricky when coming from Java, since it only checks compile time.
I've actually been working on a short post about this sort of thing over the past week, and just posted it there! Not sure how convincing it is though :)
dev.to/_darrenburns/a-simple-examp...
I just like that it decreases mental load for me.
I do not have to think about what the inputs to my functions are, what the outputs are, whether I have to think about null checks, etc.
It just helps me write safer code faster.
Also it's very self-documenting. I can always ask my IDE what other functions I can call on the output of another.
I definitely used to think they were noisy and useless but i've come around. Especially with a language like F# where most of the time the types are inferred. It's not to have some insurance around simple problems but its not magic and doesn't make everything amazing.
Something that bit me, recently: ended up having code-squirreliness because I wasn't paying attention and kept re-typing a structure. The resulting (unintentional) transformations to the stored data made for Good Times™ debugging. Wasn't till I found an excessively-pedantic linter that I figured out where the mangling was happening.
Depends on the project imo. Types are useful when building out enterprise applications with lots of inherent complexity and are meant to be read by many different developers. This is because it is easier to quickly deduce what a function expects, and what kinds of data you are working with. Additionally many editors like typescript can use the types to provide intellisense, and static type checking.
However types can get in the way and be overbearing in small projects maintained by one person where the complexity is small. It's just faster to code without types.
I'll keep it short. There are lots of merits to types, but I think the big ones are discoverability and avoiding mistakes at compile time. Couple this with an editor and you can end up with great refactoring tools. And no, types are not a silver bullet. 😉
Thanks for coming to my Ted talk.
I think that with types you can organize entities important for the business much better and don't lose yourself in big projects. There is no such thing as "untyped" language in the strict sense, they all have types behind the scenes and you need to categorize things to have a better understand of the business logic. However, when it is dynamically typed you have to have a discipline about how you code so that it doesn't become a mess that statically typed languages already have out-of-the-box.
Once, I had the idea to convert one simple React project from JavaScript to TypeScript and it was absurd how many times I had difficulties and had to scream "where the hell this variable comes from!?". It is incredible how React itself take advantage of the fact that in Javascript you can declare anything, anywhere, or don't declare at all and get away with that. Sometimes it works, sometimes it just fails silently, where most of the time you get the error while coding in statically typed languages.
There are so many articles on the technical reasons why you should use TypeScript, but very few explain why using TypeScript might make your team happier. I think it’s important to note that TypeScript’s type system is MUCH more forgiving and expressive than other type systems I’ve used like C# and Java. Jump on the TypeScript train and enjoy the happy times! :)
dev.to/cubiclebuddha/communicating...
let's say you are starting a new project with some friends, you separate task in other to be more efficient.
Then you realise that you have to work on some methods that will return an object that another teammate will use. Your teamate need and object that will have some attribute that has to match exactly meaning some mandatory fields that most have a certain type. You cannot join your teammate every time because he is in europe and the jet lag is like 7hours. Working with types will help you a lot because your teammate will make interfaces that will define the object and you will know exactly what he needs and also if some attributes are mandatory.
So types will help you work more efficiently without having to discuss every two second with your teammate
For me the main benefit of types is not correctness but developer tooling. If you're in a language/project with types, using and extending existing code is a snap because the IDE will auto-complete stuff. You'll know exactly what each class and method does and what parameters it expects. Even if you're using a third-party library with poor documentation, you can sniff out the available functionality using your IDE's code hinting feature.
As for correctness, I have yet to see evidence that typed languages are less error-prone than typed languages. Admittedly I avoid a null reference error a couple times a day when using TypeScript or C#, but I tend to think I would have found those anyway, albeit not as quickly. And if not, perhaps they didn't matter.
Personally, I think the burden of proof rests with the untyped zealots. 😛
All the points raised by others are good. All common CPUs/GPUs are inherently typed, being untyped is merely a convenience for humans.
Its a different experience I usually had experience with dynamic typed language (js, python) and later I used typescript at work. It was really great experince. First I was fighting with the type system later I started liking it more and more
P.S just give it enough time.
Bugs found at initial stages of development are cheaper to handle. Bugs can appear because of misunderstandings of requirements or lack of requirement for parts of the project.
The ways we have of reifying requirements are many but considering code, we have types, tests and documentation.
We also know that types make it unnecessary to write tests for some errors in code. For example, if something is of type String we shouldn't be able to call a method from Integer.
This means we write less tests, we right less code for our domain.
I would say this reduces then the incidental complexity of the project, since we effectively reduce the number of lines of code people have to support and learn when joining the project.
I can see why people like them, but personally I find they slow down development and restrict creativity somewhat. All depends what you're building of course.
I always find my ideas flow into working code much, much faster using untyped vars. Doing it this way also allows for more flexible code, and encourages a better mental understanding of the code. Admittedly this works better for solo coders than for sharing code with others.
Less coding errors, code readability, easier debugging, aka quality of life!
I'm on @ben side here I don't fully see the point of types.
I don't have seen any bigger proof of these claims.
So can you maybe elaborate a little bit on your claims?
Thank you <3
A statically typed environment makes you less error prone. It enforces certain basic requirements and this is a mindset that you carry with you when moving to a dynamically typed language, which I personally found very helpful when I started getting more into JavaScript, coming from a Java and (PEP8) Python background.
I think it has made me more aware of the data flow in my code and better at designing the architecture of any system.
Is @ben saying that he doesn’t like types?
I thought he was just doing a spectacular job of sparking good conversations.
That being said, using a type system isn’t always about the technical aspect. Often times there are emotional benefits:
dev.to/cubiclebuddha/communicating...
Simple, yet very rational!
Oh so you're not only a grafikart follower lol
Types are awesome.
Did that work?
Your code can prove things about your code and that's pretty awesome.
I tend to deal with a lot of unstructured unknown data so having dynamic types is often useful. Would be cool if I could lock a type on certain variables and not others...
Static typing allows for stronger tooling, catching errors and (with static analyzers) code smells earlier. It becomes more and more important as project size and teams grow larger.
type is a guide for other developer to develop in your project.
It help scale up project size.
they are not, you be happy. Debate over :P
You can catch malicious attacks on your input forms of your web apps. Debugging is lot easier and code is easier to read.
But what if can directly verify if the code is good, like with a Clojure Repl. It's Scenario 3, as you write is function it's detectly evaluated and you get the result back.
I will not. Actually, everything is a bytes in the memory.