[플레이그라운드] TDD, 클린 코드 (4) - 문자열 덧셈 계산기
2023, Sep 21
목차
전체 코드
https://github.com/Kyuyoung11/java-racingcar-playground/tree/string-add-calculator
기능 목록
1. 문자열 입력 (생략)
2. 문자열 분리
2-1. 쉼표 또는 콜론을 구분자
2-2. 커스텀 구분자
3. 합 계산
* 숫자 이외의 값 또는 음수이면 -> RuntimeException 예외 Throw
2. 문자열 분리
2-1. 쉼표/콜론 구분자
단위테스트 코드
@Test
public void splitAndSumString_쉼표또는콜론() {
int sum = StringCalculator.splitAndSum("1,2:3");
assertEquals(sum, 6);
}
코드
private static String[] _doSplit(String str) {
return str.split(",|:");
}
2-2. 커스텀 구분자 추가
단위테스트 코드
@Test
public void splitAndSumString_Custom() {
int sum = StringCalculator.splitAndSum("//;\n1;2;3");
assertEquals(sum, 6);
}
코드
private static String[] _doSplit(String str) {
Pattern pattern = Pattern.compile("(//)(.*?)(\n)");
Matcher matcher = pattern.matcher(str);
if(matcher.find()) {
str = str.substring(matcher.end());
return str.split("[,;"+matcher.group(2).trim()+"]");
}
return str.split("[,:]");
}
- Pattern, Matcher를 사용하여 특정 형식의 문자열을 추출
https://boilerplate.tistory.com/53
3. 합 계산
private static int _sum(String[] splitString) {
int sum = 0;
for (String str : splitString) {
sum += _convertStringToInt(str);
}
return sum;
}
숫자 이외의 값 또는 음수이면 -> RuntimeException 예외 Throw
단위테스트 코드
@Test
public void splitAndSum_ThrowException() throws Exception {
assertThatThrownBy(() -> StringCalculator.splitAndSum("-1,2,3"))
.isInstanceOf(RuntimeException.class);
}
코드
private static int _convertStringToInt(String str) {
try {
int number = Integer.parseInt(str);
_validate(number);
return number;
} catch (RuntimeException e) {
throw new RuntimeException();
}
}
private static void _validate(int number) {
if (number < 0) {
throw new RuntimeException();
}
}
- 숫자 이외의 값 -> try/catch로 파싱 실패하면 throw
- 음수 -> validate 메소드 따로 만들어서 throw