Chapter 4. Type safety

 

This chapter covers

  • Avoiding the primitive obsession antipattern
  • Enforcing constraints during instance construction
  • Increasing safety by adding type information
  • Increasing flexibility by hiding and restoring type information

Now that we know how to use the basic types provided by our programming language and how to compose them to create new types, let’s look at how we can make our programs safer by using types. By safer, I mean reducing the opportunity for bugs.

There are a couple of ways to achieve this by creating new types that encode additional information: meanings and guarantees. The former, which we’ll cover in the first section, removes the opportunity for us to misinterpret a value, such as mistaking a mile for a kilometer. The latter allows us to encode guarantees such as “an instance of this type will never be less than 0” in the type system. Both techniques make our code safer, as we eliminate invalid values from the set of possible values represented by a type and avoid misunderstandings as soon as we can, preferably at compile time or as soon as we instantiate our types if at run time. When we have an instance of one of our types, from then on we know what it represents and that it is a valid value.

4.1. Avoiding primitive obsession to prevent misinterpretation

4.2. Enforcing constraints

4.3. Adding type information

4.4. Hiding and restoring type information

Summary

Answers to exercises

sitemap