Code Smell | Data Clumps

Code Smell | Data Clumps

May 24, 2022

codequality
refactorit
code-smell

Hello, today we are back with the code smells refactoring series and in this case we are going to talk about code smell called Data Clumps, this code smell can be detected when we observe that certain groups of data are being used in different parts of our code.


Cause

Set of data elements, whether simple primitives, value types, or even complex types, are constantly passed together through different sections of your code base.


Example

We can see that the MarsRover class receives the value of the X and Y coordinates as a parameter, which at first is not necessarily a bad thing, right?

class MarsRover {
    constructor(
        private x: number,
        private y: number,
        private direction: string
    ) {
        //...
    }
 
    move() {
        //...
    }
 
    //...
}
 
// Use of the class
new MarsRover(100, 200, 'Example direction')

Solution

The use of X and Y as a separate set does not have to be harmful, but it can cause us different problems such as lack of cohesion, complexity when validating said data and, above all, duplication of associated logic in different parts of our code, let's see how we can fix this little smell:

class Coordinates {
    constructor(
        private x: number,
        private y: number
    ) {
        //...
    }
 
    getX() {
        return this.x
    }
 
    getY() {
        return this.y
    }
}
class MarsRover {
    constructor(
        private coordinates: Coordinates,
        private direction: string
    ) {
        //...
    }
 
    move() {
        //...
    }
}
 
// Use of the class
new MarsRover(new Coordinates(100, 200), 'Example direction')

At first glance, in this simple example, it does not seem that we gain much from this change, but we are giving a data set its own entity, which provides semantics and long-term maintainability to our code.


Benefits

  • Improves readability: you can shrink a lot of parameter lists and simplify method calling, in addition to providing semantics.

  • Improves maintainability: we avoid falling into the code smell of shotgun surgery and in this way we facilitate the management of possible changes.

If we are asked for any change regarding new logic or coordinate validation, we will be very clear about where to add it, within our Coordinates class, in addition to being able to reuse it in different parts of our code that requires coordinate treatment.


Thanks for reading me 😊

Buy Me A Coffee