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

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:

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

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