Primitive Obsession and Feature Envy

In this post I will be talking about some practices that the refactoring.guru website recommends, more specifically, primitive obsession and feature envy.

Primitive Obsession

Signs and Symptoms

  • Use of primitives instead of small objects for simple tasks (such as currency, ranges, special strings for phone numbers, etc.)
  • Use of constants for coding information (such as a constant for referring to users with administrator rights.)
  • Use of string constants as field names for use in data arrays.

Reasons for the Problem

This type smell is born when you use a primitive field to store information, instead of creating a class or object that represents this data. By the time you realize, the class is full of these storing fields and constants. Many people use primitives to simulate other data types or objects. Another example is when you use a big array full of information of different data types and access them in the class through the index.

Treatment

There are several practices you can apply to solve this problem:

Payoff

When applying these practices to solve the smell, we have various advantages:

  • The code becomes more flexible because of object utilization instead of primitives.
  • Code is more organized and the data manipulation is clear without the question of where are all these constants coming from or why are they in an array.
  • Easier finding of duplicate code.

Feature Envy

Signs and Symptoms

A method accesses the data of another object more than its own data.

Reasons for the Problem

This may happen when you move some fields to a data class. What you would want to do is move the operations with the fields to this data class.

Treatment

A simple rule is: if things change at the same time, you should keep them in the same place. If only part of a method accesses the data of another object, use Extract Method to move the part in question. If a method uses functions from several classes, determine which class has the most data that is being used. Move the method and data to this class, or you can also split the method into several parts that can be placed in different places in different classes.

Payoff

  • Less code duplication.
  • Better code organization.

Software Engineer with a passion for sharing knowledge. Also, sports lover, musician, gamer, and a tremendous food fanatic.