Design Principles and Best Practices
Primitive Obsession
Design Principles
Before we go any further, let’s know what a primitive data type is. In computer science, a primitive data type is a built-in basic data type provided by a programming language as a basic building block. Examples of the basic primitive types are character
, integer
, float
, string
, boolean
, etc. In addition, many programming languages also provide a set of composite data types as well.
What is primitive obsession?
Primitive obsession is one of the code smells that represents a case where primitives are used instead of small classes or objects to represent domain ideas. It is one of the code smells that is easy to spot. Primitive types often break encapsulation by allowing invalid values to be assigned. For instance, strings and integers do not sufficiently encapsulate concepts or business rules.
A code smell is a surface indication that usually corresponds to a deeper problem in the system. The term was first coined by Kent Beck.
For example, let’s take zip codes and phone numbers:
- When a zip code is represented as a string, it’s possible to assign values such as null, empty, some string, etc.
- Similarly, when a phone number is represented as an integer, its possible to assign values such as 98, 0, etc.
Problems with primitive types
The business rules (zip code format, etc.) we want to apply to the primitive types are typically captured somewhere away from these primitive types, as shown below, and generally duplicated throughout the application.
if (string.IsNullOrWhiteSpace(userName))
return this.BadRequest("Invalid user name.")
Solution
It’s quite simple. Just convert your primitive types into class types.