Book Image

Learn Type-Driven Development

By : Yawar Amin, Kamon Ayeva
Book Image

Learn Type-Driven Development

By: Yawar Amin, Kamon Ayeva

Overview of this book

Type-driven development is an approach that uses a static type system to achieve results including safety and efficiency. Types are used to express relationships and other assumptions directly in the code, and these assumptions are enforced by the compiler before the code is run. Learn Type-Driven Development covers how to use these type systems to check the logical consistency of your code. This book begins with the basic idea behind type-driven development. You’ll learn about values (or terms) and how they contrast with types. As you progress through the chapters, you’ll cover how to combine types and values inside modules and build structured types out of simpler ones. You’ll then understand how to express choices or alternatives directly in the type system using variants, polymorphic variants, and generalized algebraic data types. You’ll also get to grips with sum types, build sophisticated data types from generics, and explore functions that express change in the types of values. In the concluding chapters, you’ll cover advanced techniques for code reuse, such as parametric polymorphism and subtyping. By end of this book, you will have learned how to iterate through a type-driven process of solving coding problems using static types, together with dynamic behavior, to obtain more safety and speed.
Table of Contents (12 chapters)

ReasonML

We're going to explore type-driven development using ReasonML (https://reasonml.github.io/). Reason is a JavaScript-like syntax and is also a set of tools for OCaml (https://ocaml.org/). OCaml is a mature statically typed functional programming language with excellent support for object-oriented and modular programming.

We're going to write Reason code and compile it to JavaScript using the BuckleScript compiler (https://bucklescript.github.io/). BuckleScript takes input from Reason code and outputs essentially a simple subset of ES5 (that is, no ES2015-style classes, no arrow functions, and so on). This will allow us to write strongly statically typed code and see what the output JavaScript looks like with all the types stripped away.

BuckleScript, by default, outputs JavaScript files with the extension .bs.js to distinguish them from your other JS files. You can see this in the example output file, src/Ch01/Ch01_Demo.bs.js.

The Reason toolkit currently consists of:

  • A code formatting and syntax translation tool, refmt
  • An interactive code evaluation environment, rtop
  • A build manager for native-compilation projects (we won't need this one for this book), rebuild
  • A tool that provides intellisense abilities to editors, ocamlmerlin-reason

These tools work together to provide a minimal, yet powerful, development experience. Together with a good editor (we recommend Visual Studio Code), they cover most of your day-to-day development needs.

Why ReasonML?

So why have we chosen ReasonML over something else? For example, TypeScript and Flow are popular languages that target JavaScript today (among many others), but we chose Reason because:

  • It has a powerful and elegant type system, which neatly fits together many type-driven development concepts
  • Its JavaScript compiler (BuckleScript) has incredibly fast compiles, optimization, and high-quality dead-code elimination; fast compiles are great to have if you’re doing type-driven development, and performant code is great to have in any system
  • It has a very helpful and enthusiastic community that's very accessible
  • It gives you access to the mature OCaml community and its aggregated knowledge base

We will take advantage of the contrasts between the two languages to understand how statically typed Reason code is converted into dynamically typed JavaScript code yet still runs safely by design.

Getting started with ReasonML

The Reason website has a great quickstart guide as well as tutorials for setting up editor support. First, install NodeJS to get the node package manager (npm). Then, run the following:

npm install -g bs-platform
cd <your-projects-folder>
bsb –init learning-tydd-reason –theme basic-reason
cd learning-tydd-reason

Now we can do an initial compile with the following command:

bsb -make-world

The preceding command builds your entire project and its dependencies recursively. It will be almost instantaneous.

It's worth mentioning that we actually recommend running the preceding shell commands (substituting in your actual projects folder, of course), because throughout this book, we're going to arrange the code examples in the form of a single project, learning-tydd-reason, and the code examples that you type into the various given file names will fit together to make up that project.

You will almost certainly want to set up editor support in Reason so that you can get things like autocompletion and go to definition. The guides available on the ReasonML website (https://reasonml.github.io/docs/en/global-installation.html) are very helpful for this. Currently, Visual Studio Code (http://code.visualstudio.com/) is the best-supported editor; you will probably get the best results from using that.

If you are trying to decide on the install method, we would personally recommend the OPAM method (OPAM is the abbreviation of OCaml Package Manager).

Using Try Reason

Reason provides a fantastic resource for learners: an online Reason-to-JavaScript compiler and evaluator. To access it, go to the Reason website and click Try in the navigation bar at the top. You can use it to quickly try out different ideas.

Let's run through a quick example using Try Reason to get our bearings. Type in the example code from src/Ch01/Ch01_Demo.re into the Reason section of the Try Reason web app. Now add the following line after that:

let bob = makePerson(1, "Bob");

Now if you examine the output JS, you should see that the following changes have been made:

  • Types have been stripped away
  • Records have been transformed into arrays without field names (records are roughly like C structs or JavaScript objects)
  • Every declared value is explicitly exported (made public)

Note that we have purposely introduced very little actual Reason syntax in this chapter. If you are curious to explore the syntax (which is very similar to JavaScript at its core), it's best if you explore the excellent Reason website documentation. Since the focus of this book is type-driven development, in the upcoming chapters we will introduce all the syntax we will need and discuss its impact on our understanding of the code.

Going further

The ReasonML community is a helpful, fast-growing one. If you need help with anything, don't be afraid to ask. You'll only be a beginner once, and once you're comfortable, you'll be able to help other beginners. Check out the community page at https://reasonml.github.io/docs/en/community.html and drop by the discord chat as the first point of contact.