DAY 12
3
Software Development

## Feature Envy（依戀情結）

Martin Fowler 直指，這種迷戀最常發生在「資料」上。今天如果 A 類裡的某個方法，老是喜歡存取 B 類的資料來運算，這會導致 B 的細節一旦有變，A 就不得不跟著變。或是每當 B 想要改變自己身上資料的存取方式時，還得看 A 的臉色。這就造成了 A 與 B 緊密耦合，而我們並不樂見此事。

## 舉例

``````@Override
public int calculate(Transcript transcript) {

List<Course> courses = transcript.getCourses();

if (courses.isEmpty()) return 0; // 不修課跟人家領什麼獎學金！

double totalCredit = 0.001D;
double totalWeightedScore = 0D;

for (Course course : courses) {
totalCredit += course.getCredit();
totalWeightedScore += course.getScore() * course.getCredit();
}

double weightedAverage = totalWeightedScore / totalCredit;

if (weightedAverage >= 90D) {
return 15_000;
} else if (weightedAverage >= 80D) {
return 7_500;
} else {
return 0;
}
}
``````

``````    @Override
public int calculate(Transcript transcript) {

List<Course> courses = transcript.getCourses();

if (hasNoCourses(courses)) return 0; // 不修課跟人家領什麼獎學金！

double weightedAverage = calculateWeightedAverage(courses);

if (weightedAverage >= 90D) {
return 15_000;
} else if (weightedAverage >= 80D) {
return 7_500;
} else {
return 0;
}
}

private double calculateWeightedAverage(List<Course> courses) {
double totalCredit = 0.001D;
double totalWeightedScore = 0D;

for (Course course : courses) {
totalCredit += course.getCredit();
totalWeightedScore += course.getScore() * course.getCredit();
}

double weightedAverage = totalWeightedScore / totalCredit;
return weightedAverage;
}

private boolean hasNoCourses(List<Course> courses) {
return courses.isEmpty();
}
``````

``````@Override
public int calculate(Transcript transcript) {

if (transcript.hasNoCourses()) return 0; // 不修課跟人家領什麼獎學金！

double weightedAverage = transcript.calculateWeightedAverage();

if (weightedAverage >= 90D) {
return 15_000;
} else if (weightedAverage >= 80D) {
return 7_500;
} else {
return 0;
}
}
``````

## Reference

1. Martin Fowler, Refactoring : Improving the Design of Existing Code, Addison-Wesley, 2000
2. 搞笑談軟工部落格：https://teddy-chen-tw.blogspot.com/
3. GitHub Repository：https://github.com/bearhsu2/ithelp2021.git