beyond-stringly-typed

Ever gone to a website only to click a link and have it turn out like the talk title? Or written code that introduced this bug? Can types prevent this? Absolutely! Stringly typed is a term that defines most peoples usage of of types today, thanks to a horrible introduction through Java at uni.

Through real world examples that nearly every developer will have hit in their career, we can start to move beyond stringly typed code to make impossible states impossible before they become bugs for our users, or even before we run the code or tests. Along the way you will learn how some terms like ‘Parametricity’ have real world applications and not just the work of academics and will actually help you write bug proof code that is easier to reason about, and understand.

WDS18 Day 2

People tend to associated types with C and Java, which is a shame. Jared works on one of the oldest and largest codebases on the planet – Photoshop. It has millions of lines of code, some of it persisting from the first version. Yet it only has six unit tests, essentially no tests. It just has types.

Let’s define what types are. Most people think this is roughly what types give you:

  • String
  • Bool
  • Int

…and it’s tempting to say you don’t need types because you can already work out what’s a string or number. But what is a Bool, really? It’s an enum of true and false.

(Jared will use Flow from here on..)

While most programmers use those three types, they usually combine them into classes.

It’s risky to use unmarked Bool values – will you remember that true is for is_admin, or are we at risk of accidentally creating admin users because we copy and pasted?

Another problematic pattern is that people write localised type checks inside functions, which get copied into other functions; and eventually they get out of sync. Or an error is thrown way outside a useful context.

We can avoid a lot of troubles with enums. Instead of ruling out the huge variation of bad values you can’t accept, you just define the specifics of the values you want – like 1 | 2 | 3 | 4 | 5 for a star rating.

Types and tests are best of friends. Types give you feedback quickly; and they reduce the cases you have to test for by preventing bad values getting passed in.

Typed code can be optimised much more efficiently.

Problem case: URLs in strings. They break so much!

With types (specific example using phantom types) you can define absolute and relative paths, so your code won’t try to combine two absolute paths – this is how you get the broken link www.google.comlinkyoujustclicked.com

Keep your untyped code as small as possible, use types to prevent impossible states from occurring in the first place. Write tests to cover user input you don’t control.