Don’t use primitives to represent domain ideas.

Use Value Objects instead.

An account number is not an integer. Neither is a phone number or a social security number. Similarly, zip codes are not integers. At first glance, they may look like integers, but they have additional rules and restrictions. For example, a zip code that begins with zero needs to print that zero; “07093” is a valid zip code, but “7093” is not.

In the United States, phone numbers should have ten digits. Plus, “555” cannot be the digits in positions four through six; such phone numbers are always fake, and they often appear in movies and television shows.

Interest rates are not floats. Banks typically require interest rates to be recorded to a specific number of significant digits. Also, there are often rules against having negative numbers for interest rates.

An amount of money is not a float. Most financial systems do not recognize any amount less than 0.01 dollars as valid. While some applications choose to represent money by using an integer to represent pennies, this is not a good choice either. You can always multiply two integers together, but you should never multiply two money amounts together. There is no such thing as a “dollars squared” unit of measurement.

Instead, use the Value Object pattern. Creating small classes representing these domain ideas gives you much more control over their behavior. It also limits the number of actions that can be applied to these objects, reducing the chances of invalid operations.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: