Chapter 24. Types
Types are essentially assertions about a program. And I think it’s valuable to have things be as absolutely simple as possible, including not even saying what the types are.
Dan Ingalls, Coders at Work: Reflections on the Craft of Programming
24.0 Introduction
Types are the most important concept in classification languages. This is true for static and strongly typed languages and also for dynamically typed ones. Dealing with them is not easy and you have many flavors, from very restrictive ones to lazier ones.
24.1 Removing Type Checking
Problem
You type-check your arguments.
Solution
Trust your collaborators. Don’t check who they are. Ask them to do it instead.
Discussion
Avoid kind()
, isKindOf()
, instance()
, getClass()
, typeOf()
, etc., and don’t use reflection and metaprogramming for domain objects (see Chapter 23, “Metaprogramming”). Avoid checking for undefined. Use complete objects (see Recipe 3.7, “Completing Empty Constructors”), and avoid nulls (see Recipe 15.1, “Creating Null Objects”) and setters. Favor immutability and you will never have undefined types or accidental ifs.
Here are examples of type checking:
if
(
typeof
(
x
)
===
'undefined'
)
{
console
.
log
(
'variable x is not defined'
);
}
function
isNumber
(
data
)
{
return
(
typeof
data
===
'number'
);
}
And here’s a complete type-checking example:
function
move
(
animal
)
{
if
(
animal
instanceof
Rabbit
)
{
animal
.
run
()
}
if
(
animal
instanceof
Seagull
)
{
animal
.
fly
()
}
}
class
Rabbit
{
run
()
{
console ...
Get Clean Code Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.