Skip to main content

Command Palette

Search for a command to run...

Code Smell 63 - Feature Envy

If your method is jealous and doesn't trust in delegation, you should start to do it.

Updated
2 min read
Code Smell 63 - Feature Envy
M

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

TL;DR: Don't abuse your friend objects.

Problems

  • Coupling

  • Low Reuse

  • Low Testability

  • Bad Responsibilities Assignment

  • Bijection Fault

Solutions

  1. Move the method to the appropriate class.

Sample Code

Wrong

class Candidate {

 void printJobAddress(Job job) {

   System.out.println("This is your position address");

   System.out.println(job.address().street());
   System.out.println(job.address().city());
   System.out.println(job.address().ZipCode());
 } 
}

Right

class Job {

 void printAddress() {

   System.out.println("This is your job position address");

   System.out.println(this.address().street());
   System.out.println(this.address().city());
   System.out.println(this.address().ZipCode());

  // We might even move this responsibility directly to the address!
  // Some address information is relevant to a job and not for package tracking
 } 
}

class Candidate {
  void printJobAddress(Job job) {
    job.printAddress();
  }
}

Detection

Some linters can detect a sequential pattern of collaborations with another object.

Tags

  • Coupling

Conclusion

  • We should assign responsibilities according to real object mappers and avoid abusing other objects' protocol.

Relations

More info

Credits

Photo by Hisu lee on Unsplash


We argue that design practices which take a data-driven approach fail to maximize encapsulation because they focus too quickly on the implementation of objects. We propose an alternative object-oriented design method which takes a responsibility-driven approach.

Rebecca Wirfs-Brock



This article is part of the CodeSmell Series.

R
Rodrigo5y ago

Great advice Maxi 👏

The job instance knows its properties, so by moving the print responsibility close to their source of change; we make the candidate class depend on one point of change rather than multiples attributes in the job class 👌

M

yes ! i will add this to the article!

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.