예제 코드
public double getTotalOutstandingAndSendBill() {
double result = customer.getInvoices().stream()
.map(Invoice::getAmount)
.reduce((double) 0, Double::sum);
sendBill();
return result;
}
private void sendBill() {
emailGateway.send(formatBill(customer));
}
- 기존에 두개로 묶여있던 질의함수와 변경함수가 있는데 변경함수와 질의함수를 찢어서 나눈 코드는 아래와 같이 변경하면된다.
public double getTotalOutstanding() {
return customer.getInvoices().stream()
.map(Invoice::getAmount)
.reduce((double) 0, Double::sum);
}
public void SendBill() {
emailGateway.send(formatBill(customer));
}
@Test
void totalOutstanding() {
Billing billing = new Billing(new Customer("keesun", List.of(new Invoice(20), new Invoice(30))),
new EmailGateway());
assertEquals(50d, billing.getTotalOutstandingAndSendBill());
}
public String alertForMiscreant(List<Person> people) {
for (Person p : people) {
if (p.getName().equals("Don")) {
setOffAlarms();
return "Don";
}
if (p.getName().equals("John")) {
setOffAlarms();
return "John";
}
}
return "";
}
public void alertForMiscreant(List<Person> people) {
for (Person p : people) {
if (p.getName().equals("Don")) {
setOffAlarms();
}
if (p.getName().equals("John")) {
setOffAlarms();
}
}
}
public String findMiscreant(List<Person> people) {
for (Person p : people) {
if (p.getName().equals("Don")) {
return "Don";
}
if (p.getName().equals("John")) {
return "John";
}
}
return "";
}
- 기능이 두개로 합쳐져있는 변경함수와 질의함수를 두개로 나누어 메서드로 값을 설정했다.