Skip to content

Commit 6e1cc54

Browse files
committed
refactor. 메소드 책임 분할
1 parent 3357666 commit 6e1cc54

File tree

1 file changed

+34
-25
lines changed

1 file changed

+34
-25
lines changed

src/main/java/domain/StringCalculator.java

Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,13 @@ public class StringCalculator {
1313
private final String delimeterRegex = "[,|:]";
1414

1515
public int calculate(String str) {
16-
String[] tokens;
17-
String customDelimeter;
18-
1916
if (str == null || str.isBlank()) {
2017
throw new RuntimeException(EMPTY_STRING);
2118
}
2219

23-
customDelimeter = findCustomDelimeter(str);
24-
25-
if (customDelimeter == null) {
26-
tokens = str.split(delimeterRegex);
27-
} else {
28-
tokens = str.substring(str.indexOf("\n") + 1)
29-
.split(Pattern.quote(customDelimeter));
30-
}
31-
20+
String customDelimeter = findCustomDelimeter(str);
21+
String strNumbers = extractNumber(str, customDelimeter);
22+
String[] tokens = splitTokens(strNumbers, customDelimeter);
3223
List<Integer> numbers = parseNumber(tokens);
3324

3425
return add(numbers);
@@ -49,24 +40,42 @@ public String findCustomDelimeter(String str) {
4940
return str.substring(startDelimeterIdx + 2, endDelimeterIdx);
5041
}
5142

43+
public String extractNumber(String str, String customDelimeter) {
44+
if (customDelimeter != null) {
45+
return str.substring(str.indexOf("\n") + 1);
46+
}
47+
48+
return str;
49+
}
50+
51+
public String[] splitTokens(String strNumbers, String customDelimeter) {
52+
if (customDelimeter == null) {
53+
return strNumbers.split(delimeterRegex);
54+
}
55+
56+
return strNumbers.split(Pattern.quote(customDelimeter));
57+
}
58+
5259
public List<Integer> parseNumber(String[] tokens) {
5360
return Arrays.stream(tokens)
54-
.map(token -> {
55-
try {
56-
int number = Integer.parseInt(token.trim());
57-
58-
if (number < 0) {
59-
throw new RuntimeException(NEGATIVE_NUMBER_NOT_ALLOWED);
60-
}
61-
62-
return number;
63-
} catch (NumberFormatException ex) {
64-
throw new RuntimeException(INVALID_STRING);
65-
}
66-
})
61+
.map(this::parseTokenToInt)
6762
.toList();
6863
}
6964

65+
public int parseTokenToInt(String token) {
66+
try {
67+
int number = Integer.parseInt(token.trim());
68+
69+
if (number < 0) {
70+
throw new RuntimeException(NEGATIVE_NUMBER_NOT_ALLOWED);
71+
}
72+
73+
return number;
74+
} catch (NumberFormatException ex) {
75+
throw new RuntimeException(INVALID_STRING);
76+
}
77+
}
78+
7079
public int add(List<Integer> numbers) {
7180
return numbers.stream()
7281
.mapToInt(Integer::intValue)

0 commit comments

Comments
 (0)