Feature envy#

Feature envy

Feature envy is a code smell that occurs when a method is more interested in a class other than the one it is in. This smell indicates that the method is using more features of another class than its own, which can lead to high coupling and low cohesion between the classes.

The term “feature envy” is derived from the idea that the method is envious of the features of another class and is trying to access or manipulate them directly. This smell can indicate a design issue where responsibilities are not well-distributed among classes, leading to poor encapsulation and modularity.

The idea of a good object-oriented design is to encapsulate data and behavior within classes, so that each class is responsible for its own data and operations (behavior). When a method in one class is more interested in the data or behavior of another class, it suggests that the responsibilities are not properly distributed and that the classes are not well-designed.

The Law of Demeter is closely associated to this smell.

Feature envy can lead to several problems:

  • High Coupling: When a method is dependent on the features of another class, it creates a tight coupling between the two classes. Changes in one class can have a cascading effect on the other, making the code harder to maintain and evolve.

  • Low Cohesion: The method’s interest in another class’s features indicates that the responsibilities are not well-distributed. This can lead to classes that do not have a clear and focused purpose, reducing the code’s cohesion.

  • Code Duplication: If multiple methods in a class exhibit feature envy for the same external class, it can lead to code duplication. This redundancy makes the code harder to maintain and can introduce inconsistencies.

Solution#

  • Extract Method: Identify the code that is accessing features of another class and extract it into a separate method within the class that owns the data. This will help in encapsulating the behavior and reducing feature envy (see also Functions are Friends).

  • Move Method: If the method is consistently accessing features of another class, consider moving the method to the class that owns the data. This will improve encapsulation and ensure that the responsibilities are properly distributed.