HINT)
String[] tokens = text.split(",|:");
public class StringCalculatorTest {
...
@Test
public void add_쉼표_또는_콜론_구분자() throws Exception {
assertEquals(6, cal.add("1,2:3"));
}
}
public class StringCalculator {
public int add(String text) {
if (isBlank(text)) {
return 0;
}
return sum(toInts(split(text)));
}
private boolean isBlank(String text) {
return text == null || text.isEmpty();
}
private String[] split(String text) {
// return text.split(",");
return text.split(",|:");
}
private int[] toInts(String[] values) {
int numbers[] = new int[values.length];
for (int i = 0; i < values.length; i++) {
numbers[i] = Integer.parseInt(values[i])
}
return numbers;
}
private int sum(int[] numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
}
이와 같이 메서드를 잘 분리해 놓으면 새로운 요구사항이 발생할 경우 해당 메서드만 수정사항을 반영하는 것이 가능하다. 상당히 작은 부분이 수정되었기 때문에 추가적인 리팩토링 없이 다음 단계로 넘어간다.
참고도서 : https://roadbook.co.kr/169
[신간안내] 자바 웹 프로그래밍 Next Step
● 저자: 박재성 ● 페이지: 480 ● 판형: 사륙배변형(172*225) ● 도수: 1도 ● 정가: 30,000원 ● 발행일: 2016년 9월 19일 ● ISBN: 978-89-97924-24-0 93000 [강컴] [교보] [반디] [알라딘] [예스24] [인터파크] [샘
roadbook.co.kr
'교재 실습 > 자바 웹 프로그래밍 Next Step' 카테고리의 다른 글
2.4.4.6 문자열 계산기에 음수를 전달하는 경우 RuntimeException 예외를 throw 한다 (0) | 2025.01.11 |
---|---|
2.4.4.5 문자 사이에 커스텀 구분자를 지정할 수 있다 (0) | 2025.01.10 |
2.4.4.3 숫자 두개를 쉼표(,) 구분자로 입력할 경우 두 숫자의 합을 반환한다 (0) | 2025.01.08 |
2.4.4.2 숫자 하나를 문자열로 입력할 경우 해당 숫자를 반환한다 (0) | 2025.01.07 |
2.4.4.1 빈 문자열 또는 null 값을 입력할 경우 0을 반환해야 한다 (0) | 2025.01.07 |
댓글