Code Smell 89 - Math Feature Envy

Maxi Contieri - Oct 4 '21 - - Dev Community

One class calculating formulas for another class.

TL;DR: Leave the formulas to the objects gathering the information.

Problems

  • Declaratively

  • Low reuse

  • Real-world concept missing

  • Encapsulation

Solutions

  1. Move the math formula to the class

  2. Search for real-world abstractions

Sample Code

Wrong

function area(rectangle) { 
  return rectange.width * rectangle.height;
  //Notice we are sending consecutive messages to
  //the same object and doing calculations
}
Enter fullscreen mode Exit fullscreen mode

Right

class Rectangle {
    constructor(width, height, color) { 
         this.height = height;
         this.width = width;
    }

    area() {
        return this.width * this.height;
    }
}
Enter fullscreen mode Exit fullscreen mode

Detection

Since many cascading messages are sending to the same object, we can detect a pattern.

Tags

  • Encapsulation

  • Coupling

Conclusion

This is a very basic smell. If we are manipulating another object characteristics, we should let it do it the maths for us.

Relations

More Info

Credits

Photo by Michal Matlon on Unsplash


Computer science is not about machines, in the same way that astronomy is not about telescopes. There is an essential unity of mathematics and computer science.

Michael R. Fellows


This article is part of the CodeSmell Series.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .