Lesson 4
Feature Envy: Move Method Refactoring with TDD
Introduction and Context Setting

In software design, understanding and addressing code smells, such as "Feature Envy", is vital for maintaining and improving code quality. Code smells are indicators of potential issues in your codebase that may hinder readability and maintainability. Feature Envy specifically arises when a method in a class has excessive interactions with the data of another class, often leading to a tangled code structure that is difficult to test and maintain.

Refactoring is the process of restructuring existing code to enhance its readability, maintainability, and performance without altering its external behavior. Common refactoring patterns, such as the Move Method, can be employed to address code smells like Feature Envy. This involves relocating methods to the class that holds the data they depend on, thus reducing unnecessary dependencies and improving cohesion.

In this course, we employ Test Driven Development (TDD) practices using TypeScript and Jest. TypeScript offers significant advantages with its robust type system, aiding in error reduction at compile time, while Jest provides an efficient and straightforward testing framework. We emphasize the TDD cycle — Red, Green, Refactor — to incrementally evolve the code with confidence, ensuring each step is supported by a comprehensive suite of tests.

What is Feature Envy?

Feature Envy is a code smell that occurs when a method in one class interacts too heavily with the data of another class, showing an unwarranted interest in the features of that class. This often manifests when a method accesses the properties or calls the methods of another class more frequently than it operates on its own data. This anti-pattern suggests that the method may be misplaced and that it logically belongs in the class it is so interested in.

This code smell is problematic for several reasons:

  1. Poor Encapsulation: Feature Envy often breaches encapsulation, which is the foundation of object-oriented design. By reaching across class boundaries to manipulate another class's data, it undermines the principle that each class should handle its own data and behavior.

  2. Increased Coupling: When classes become too intertwined due to Feature Envy, the coupling between classes increases. High coupling means changes in one class can ripple through others, increasing the difficulty and risk of making changes.

  3. Reduced Cohesion: A class with methods affected by Feature Envy lacks proper cohesion, meaning its methods are not focusing on its primary responsibility. This dilution of responsibility makes understanding and maintaining the class more complex.

  4. Testing Complexity: Feature Envy can complicate unit testing because methods are reliant on external data. This may necessitate intricate test setups or the need for mocking external dependencies, reducing test simplicity and effectiveness.

To mitigate Feature Envy, we leverage the refactoring pattern Move Method, relocating the envious method to the class whose data it primarily operates on. This realignment enhances the code by promoting greater cohesion, reducing coupling, and adhering to the object's design principles, leading to more maintainable and robust software.

Overview of the Current Codebase

In the coming practices, we'll focus on a grade-analyzer component that analyzes student grades. However, certain methods in the GradeAnalyzer class exhibit Feature Envy by deeply interacting with Student class data.

Consider the calculateFinalGrade() method in GradeAnalyzer, which calculates a student's final grade based on assignments and late submissions. This method heavily manipulates the grade data from the Student class, suggesting a lack of responsibility boundaries between these classes. Such scenarios point to an opportunity for improvement by refactoring via the Move Method technique to enhance focus and reduce dependencies.

We shall now proceed to demonstrate how to identify and address this issue using the TDD workflow.

Example: Identifying Feature Envy

To successfully identify Feature Envy, focus on methods within a class that interact disproportionately with another class’s data. In our case, within the code, observe the function calculateFinalGrade() in GradeAnalyzer, which processes the grades owned by the Student class.

Here’s a glimpse of the current method:

TypeScript
1calculateFinalGrade(): number { 2 const grades = this.student.getGrades(); 3 if (grades.length === 0) return 0; 4 5 let totalEarned = 0; 6 let totalPossible = 0; 7 8 for (const grade of grades) { 9 if (this.isLateSubmission(grade)) { 10 totalEarned += grade.score * 0.9; // 10% penalty for late submissions 11 } else { 12 totalEarned += grade.score; 13 } 14 totalPossible += grade.totalPoints; 15 } 16 17 return (totalEarned / totalPossible) * 100; 18}

Since calculateFinalGrade relies on Student data, any changes to Student’s data structure might require updates to calculateFinalGrade, creating a tight dependency. calculateFinalGrade frequently accesses this.student.getGrades() and operates on each grade item’s data, suggesting that it may be better suited to the Student class. Additionally, test for calculateFinalGrade may require a Student instance with specific data, making the testing process more complex. Lastly, it may result in a reduced readability. When a method interacts heavily with another class’s data, understanding which class owns the data becomes confusing.

Refactor: Move Method to Class

When we refactor the details of how grades are scored, the calculateFinalGrade() method can focus only on the logic it cares about: aggregating grades for a final grade.

TypeScript
1calculateFinalGrade(): number { 2 if (this._grades.length === 0) return 0; 3 4 let totalEarned = 0; 5 let totalPossible = 0; 6 7 for (const grade of this._grades) { 8 totalEarned += grade.scoreWithLatePenalty; 9 totalPossible += grade.totalPoints; 10 } 11 12 return (totalEarned / totalPossible) * 100; 13}
Review/Summary and Heads Up About Practice Exercises

In this lesson, we addressed Feature Envy using the Move Method refactoring technique. By identifying methods overly interested in another class’s data and relocating them appropriately, you experienced improved code organization and cohesion.

Key takeaway: Feature Envy poses challenges in maintainability; refactoring via TDD — Red, Green, Refactor — enables a more robust codebase.

Please venture into the upcoming practice exercises to consolidate your understanding of these concepts in different scenarios. Remember, the path to cleaner code involves continuous, mindful improvement. Keep practicing, and congratulations on progressing to this stage of mastering TDD in TypeScript!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.