Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2단계 - 문자열 덧셈 계산기 #5925

Merged
merged 4 commits into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file removed src/main/java/.gitkeep
Empty file.
54 changes: 54 additions & 0 deletions src/main/java/step2/NumberSeparator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package step2;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import utils.StringUtils;

public class NumberSeparator {

private static final String DEFAULT_DELIMITER = "[,:]";
private static final String DELIMITER_FIND_REGEX = "//(.)\n(.*)";
Comment on lines +11 to +12
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

상수 👍


public List<Integer> separate(String input) {
if (StringUtils.isEmpty(input)) {
return List.of(0);
}
if (StringUtils.isNumeric(input)) {
return List.of(Integer.parseInt(input));
}
Pattern pattern = Pattern.compile(DELIMITER_FIND_REGEX);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pattern.compile 은 상수화 하는것도 좋을것 같아요!

구현체를 살펴보면 매번 새로운 Pattern 을 생성하기 때문이에요 🙃

    /**
     * Compiles the given regular expression into a pattern.
     *
     * @param  regex
     *         The expression to be compiled
     * @return the given regular expression compiled into a pattern
     * @throws  PatternSyntaxException
     *          If the expression's syntax is invalid
     */
    public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
    }

Matcher matcher = pattern.matcher(input);

String[] values;
if (matcher.find()) {
String customDelimiter = matcher.group(1);
values = matcher.group(2).split(customDelimiter);
} else {
values = input.split(DEFAULT_DELIMITER);
}
Comment on lines +28 to +30
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📖 객체지향 생활 체조 원칙
규칙 2: else 예약어를 쓰지 않는다.

를 지켜서 해보는것도 좋을것 같아요! :)

return convertStringArrayToIntegerList(values);
}

private List<Integer> convertStringArrayToIntegerList(String[] values) {
List<Integer> members = new ArrayList<>();
for (String value : values) {
members.add(parseAndCheck(value));
}
return members;
}

private Integer parseAndCheck(String input) {
int value;
try {
value = Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new RuntimeException("숫자가 아닌 값이 입력되었습니다.");
}
if (value < 0) {
throw new RuntimeException("음수는 입력할 수 없습니다.");
}
Comment on lines +46 to +51
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

return value;
}
}
21 changes: 21 additions & 0 deletions src/main/java/step2/StringAddCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package step2;


import java.util.List;

public class StringAddCalculator {

private final static NumberSeparator numberSeparator = new NumberSeparator();


public static int splitAndSum(String o) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

의미있게 변수명을 지어보는것도 좋을것 같아요 :)

List<Integer> splitNumber = numberSeparator.separate(o);
return sum(splitNumber);
}

private static int sum(List<Integer> splitNumber) {
return splitNumber.stream()
.mapToInt(Integer::intValue)
.sum();
}
}
18 changes: 18 additions & 0 deletions src/main/java/utils/StringUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package utils;

public class StringUtils {

public StringUtils() {
}
Comment on lines +5 to +6
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

static 메서드만 갖고 있는 클래스의 기본생성자를 열어두셨네요.
이유를 알 수 있을까요? 🤔

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고민의 흔적이 남아있던것같습니다. 제거하는 쪽으로 하겠습니다


public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}

public static boolean isNumeric(String str) {
if (isEmpty(str)) {
return false;
}
return str.matches("\\d+");
}
}
Empty file removed src/test/java/.gitkeep
Empty file.
54 changes: 54 additions & 0 deletions src/test/java/step2/StringAddCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package step2;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class StringAddCalculatorTest {

@Test
public void splitAndSum_null_또는_빈문자() {
int result = StringAddCalculator.splitAndSum(null);
assertThat(result).isEqualTo(0);

result = StringAddCalculator.splitAndSum("");
assertThat(result).isEqualTo(0);
}

@Test
public void splitAndSum_숫자하나() throws Exception {
int result = StringAddCalculator.splitAndSum("1");
assertThat(result).isEqualTo(1);
}

@Test
public void splitAndSum_쉼표구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("1,2");
assertThat(result).isEqualTo(3);
}

@Test
public void splitAndSum_쉼표_또는_콜론_구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("1,2:3");
assertThat(result).isEqualTo(6);
}

@Test
public void splitAndSum_custom_구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("//;\n1;2;3");
assertThat(result).isEqualTo(6);
}

@Test
public void splitAndSum_negative() throws Exception {
assertThatThrownBy(() -> StringAddCalculator.splitAndSum("-1,2,3"))
.isInstanceOf(RuntimeException.class);
}

@Test
public void splitAndSum_문자포함() throws Exception {
assertThatThrownBy(() -> StringAddCalculator.splitAndSum("1,2,test"))
.isInstanceOf(RuntimeException.class);
}
Comment on lines +43 to +53
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예외메세지를 추가로 정의해주셨으니, 검증도 같이하는건 어떨까요?

}
6 changes: 3 additions & 3 deletions src/test/java/study/StringTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@
public class StringTest {

@Test
void Split() {
void split() {
String[] splitText = "1,2".split(",");
assertThat(splitText).containsExactly("1", "2");
}

@Test
void Substring() {
void substring() {
String text = "(1,2)";
String substringText = text.substring(1, text.length() - 1);
assertThat(substringText).isEqualTo("1,2");
}

@Test
void CharAt() {
void charAt() {
String text = "abc";
assertThat(text.charAt(0)).isEqualTo('a');
assertThat(text.charAt(1)).isEqualTo('b');
Expand Down