4 Type Safety

 

This chapter covers

  • The “primitive obsession” anti-pattern
  • 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 using types. By safer we mean reducing the opportunity for bugs.

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

4.1       Avoiding Primitive Obsession to Prevent Misinterpretation

4.1.1 The Mars Climate Orbiter

4.1.2 The Primitive Obsession Anti-Pattern

4.1.3 Exercise

4.2       Enforcing Constraints

4.2.1 Enforcing Constraints with The Constructor

4.2.2 Enforcing Constraints with a Factory

4.2.3 Exercise

4.3       Adding Type Information

4.3.1 Type Casting

4.3.2 Tracking Types Outside the Type System

4.3.3 Common Typecasts

4.3.4 Exercises

4.4       Hiding and Restoring Type Information

4.4.1 Heterogenous Collections

4.4.2 Serialization

4.4.3 Exercises

4.5       Summary

4.6       Answers to Exercises

sitemap