DAY 5
3
Software Development

## 透過被依賴對象，控制測試目標邏輯

``````@Data
@AllArgsConstructor
public class Course {
private String name;
private int score;
}
``````
``````@Data
public class Transcript {
private List<Course> courses;

public Transcript(Course... courses) {
this.courses = Arrays.asList(courses);
}
}
``````

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

List<Course> courses = transcript.getCourses();
if (courses.isEmpty()) return 0; // 不修課跟人家領什麼獎學金！

int total = courses.size();
int achieved = 0;
for (Course course : courses) {
if (course.getScore() >= 80) {
achieved++;
}
}
double rate = (double) achieved / total;

if (rate >= (double) 1 / 2) {
return 10_000;
} else if (rate >= (double) 1 / 3) {
return 5_000;
} else {
return 0;
}
}
``````

``````@Test
void NO_courses() {
ScholarshipService service = new ScholarshipService();

int actual = service.calculate(new Transcript(/*nothing*/));

Assertions.assertEquals(0, actual);
}
``````

``````@Test
void full_scholarship() {

ScholarshipService service = new ScholarshipService();

int actual = service.calculate(new Transcript(
new Course("Algorithm", 70),
new Course("Computer Internet", 80),
new Course("Operating System", 90)

));

Assertions.assertEquals(10_000, actual);
}
``````

## 瞬間飆高的程式複雜度。

「到底為什麼這麼麻煩啊？我到底做錯了什麼事啊？」

## 瘦到雨都淋不到：單一職責原則

Uncle Bob 在 Clean Code 談到函式時表示：「函式應該要做一件事。它應該要把這件事做好，並且只能做這件事。」書中也另外補充說明道：「一個函式應該要只能因為一個理由而被修改。」

1. 加個 if，防禦性編程
2. 複製一份出來改，以免破壞原邏輯

## 獎學金的範例，就管太多了...

1. 學生的身份
2. 學生有沒有修一門以上的課
3. 學生符合哪種獎學金資格
4. 每種資格該發多少錢

## Reference

1. Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship. Upper Saddle River, NJ: Prentice Hall, 2009.
2. GitHub: https://github.com/bearhsu2/ithelp2021.git