In this blog post, Anna Makowska talks about primitive obsessions code smells and what you can do to fix them. The author chose to focus on primitive bbession code smell because some smells are harder for developers to detect intuitively.
“Primitive data types are basic built-in building blocks of a language. They’re usually typed as int, string, or constants. As creating such fields is much easier than making a whole new class, this leads to abuse. Therefore, this makes this smell one of the most common ones.”
Examples
- Using primitive data types to represent domain ideas. For example, using an integer to represent an amount of money or a string for a phone number.
- Using variables or constants for coding information. An often-encountered case is using constants for referring to users roles or credentials (like const USER_ADMIN = 1).
- Using strings as field names in data arrays.
Consequences
- Code becomes less flexible because of use of primitives instead of objects.
- Primitive data types are much harder to control. As a result, we may get variables that aren’t valid (supported by the type) or meaningful.
- Primitives are often related to dedicated business logic. Therefore, leaving this logic unseparated may violate the Single Responsibility Principle and the Open/Closed Principle.
- When data type logic is not separated in a dedicated class, adding a new type or behavior makes the basic class grow and get unwieldy.
- By using primitives, the developer loses the benefits that come with object-oriented design, like data typing by class name or type hinting.
Replace Data Value With Object
- Instead of a set of primitive values, the programmer has full-fledged classes with all the benefits that object-oriented programming has to offer (typing data by class name, type hinting, etc.).
- There is no need to worry about data validation, as only expected values can be set.
- When relationship logic extends, it will be placed in one place dedicated to it.
I chose this resource because it had plenty of good information on the primitive obsession code smell, when it’s going to lead to problems and how to fix that. I learned two more fixes, Replace Type Code With Subclasses, State, or Strategy (patterns) and Replace Array With Object for when “values of a coded type aim to control the behavior of the program.” I felt the content to be quality content from a author who has experience with spotting and fixing code smells. I will use this information in the future, by keeping an eye out for primitive obsession code smells.
The post Code Quality: Fighting Primitive Obsession Code Smells appeared first on code friendly.
From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.
