DEV Community

Ben Halpern
Ben Halpern

Posted on

Convince me that types are awesome

Suppose I've mostly used untyped programming languages and don't have a great appreciation for types.

Let's do some convincing!

Latest comments (60)

Collapse
 
vdeolali profile image
Vikas Deolaliker

You can catch malicious attacks on your input forms of your web apps. Debugging is lot easier and code is easier to read.

Collapse
 
jasman7799 profile image
Jarod Smith

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.

Collapse
 
arschles profile image
Aaron Schlesinger

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:

  • More self-documenting
    • what does this function expect?
    • how is it gonna use it?
    • what is it gonna return?
  • IDEs can provide richer & faster intellisense / code completion / go to definition / inline docs \
    • Check out XCode for Swift and Visual Studio for C#. Both are 🔥 at this stuff for their languages
  • Usually less boilerplate-ey tests to write
  • Some groups of runtime errors are impossible. Some examples:
    • In some languages, there's a type of array that cannot be empty, so myarray[0] will never throw
    • Others have literally no exceptions. Functions that might fail will always return a type that can either be a successful value, or an error. You have to deal with both or your code won't compile

Cons:

  • Some typed languages have horrific compiler error messages if you mess up. Good luck figuring out what you did wrong, let alone fixing it
  • Typed languages often have a steeper learning curve
    • There are exceptions on either side, of course!
    • Go is easy to pick up for lots of folks
    • ... and Ruby has magic in it that can trip folks up pretty early on in their learning
  • There's math behind type systems (no joke! "Category Theory" on wikipedia). Some languages will force you to learn some of that, even if they don't mean to
  • Some typed languages have "generics" - being able to write functions that can handle any type. It's handy and powerful, but these functions can be super confusing for the person calling the function

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!

Collapse
 
danielw profile image
Daniel Waller (he/him)

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.

Collapse
 
vasilvestre profile image
Valentin Silvestre

Oh so you're not only a grafikart follower lol

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

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.

Collapse
 
ferricoxide profile image
Thomas H Jones II

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.

 
gklijs profile image
Gerard Klijs

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.

Collapse
 
bradtaniguchi profile image
Brad • Edited

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.

  1. Developing with types gives you better documentation at your fingertips since types provide better context, and auto-completion.
    • Its easier to write code
  2. Developing with types gives you more fail-safes in your code
    • Your code gets harder to screw up
    • Etc. Typos/invalid arguments/invalid syntax all explodes at the time of writing, rather than at run-time.
  3. Developing with types gives you more fail-safes when using external code
    • More reliable interactions between your code and libraries
    • Ex. Version 3 of the package had breaking changes, all you code now explodes at compile time, rather than at run-time.
  4. Refactoring massive projects becomes stupidly easy to handle.
    • Cleaner, safer, faster code refactors
    • Ex. Rename a User object's name property to fullName is as easy.
  5. Projects don't fail because "you don't write code fast enough" they may fail because you can't update your code easily enough, or your code is a mess
    • Typescript allows you to iterate on existing code faster, and safer, resulting in saved $$$
    • (see refactor example)
  6. Your probably already using some typechecking/typescript via VSCode's built in typechecking features

Make the code work for you, don't work for the code!

Collapse
 
gklijs profile image
Gerard Klijs

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.

Collapse
 
patrick profile image
Patrick Ziegler

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:

var x = {'prop': "text"};
var y = x.porp;

y is undefined here, you only notice this once you get a strange result somewhere or, if you're lucky, get a TypeError: 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:

struct foo {
  char* prop;
}

...

struct foo x = {"text"};
char* y = x.porp;

This will immediately give you a compiler error:

error: ‘struct foo’ has no member named ‘porp’; did you mean ‘prop’?
Collapse
 
thejoezack profile image
Joe Zack

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.

Collapse
 
aswathm78 profile image
Aswath KNM

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

JavaScript’s dynamic types were hard to adjust to at first, but once I got used to them, it was like coming out of a long, dark tunnel and into the light.

I just thought you'll be convinced when some one with more experience offer their wisdom

His thoughts on types

Static types can be very useful to help document functions, clarify usage, and reduce cognitive overhead. For example, I usually find Haskell’s types to be helpful, low-cost, pain-free, and unobtrusive

Collapse
 
lexlohr profile image
Alex Lohr

For 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).

Collapse
 
pinotattari profile image
Riccardo Bernardini

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

type Filename is new String;
type Package_Name is new String;

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.