EN
close
0
0 product
totalNT$ 0
Checkout
Member Login
Verify Code
Forget?
Register account

CodeSmell - Primitive Obsession

Description

When it comes to the quality of code, it's about whether it can solve problems and whether it's easy to understand. One day, when I encountered code smells, like Long Method and Large Class, they seemed okay, quite understandable. Next: Primitive Obsession?! This... was too difficult for me to grasp, so I decided to write an article to help myself practice.

Primitive Type: The most basic code types provided by a programming language, such as int, string, decimal in C#...

Obsession: I found a fitting Chinese description: being fixated on something.

So, Primitive Obsession would be: being fixated on primitive types!

When thinking about what being fixated on primitive types means, based on past experiences, before storing data in a database, it's usually converted to primitive types for data transfer. If that's the case, using primitive types frequently should be quite normal, right? However, if we use the term "obsession," it means using them where they shouldn't be used.

When searching for this Code Smell online, a common example that came up was URL.

A URL consists of various components:

When we use a primitive type like string to store a URL, we lose the ability to access its components directly. Later, if we want to access them again, we have to write parsing code to extract the desired elements. However, I still didn't quite understand how significant the impact would be.

Example from Work: In my past work experiences, I encountered scenarios where users needed to be created. If we were developing an account management service API, it might look something like this:

At first glance, it seems fine, but then things start happening:

username: May need to validate the format of the username. May need to check for duplicates. password: May need to validate the password. Encryption may be required for passwords.

Because of the primitive types, we can't efficiently obtain validation results, but validation is still necessary. This leads to the emergence of more validation channels: Helper, Extension Method, UserValidationClass... and code smells gradually appear. Can you imagine if there were similar APIs like update-password, search-member... with similar input parameters?

Expanding this Primitive Obsession directly into CreateUserRequest would also cause CreateUserRequest to become a very large class. Then there's the issue of another request that looks similar but can't be reused, leading to rewriting validation.

Is there a better solution?

Read more...

Article cited from https://hwchw.medium.com/