Skip to content

feat: StringAddCalculator 추가 #5906

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

Merged
merged 3 commits into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
39 changes: 39 additions & 0 deletions src/main/java/StringAddCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringAddCalculator {
static int splitAndSum(String text) {
if (text == null || text.isEmpty()) {
return 0;
}

Matcher m = Pattern.compile("//(.)\n(.*)").matcher(text);
Copy link

Choose a reason for hiding this comment

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

Pattern.compile("//(.)\n(.*)") 은 상수화 하는것도 좋을것 같아요!

구현체를 살펴보면 매번 새로운 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);
    }

Copy link
Author

Choose a reason for hiding this comment

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

pattern 상수화 했습니다!

if (m.find()) {
String customDelimiter = m.group(1);
String[] numbers = m.group(2).split(customDelimiter);
return sumNumbers(numbers);
} else {
try {
int number = Integer.parseInt(text);
if (number < 0)
throw new RuntimeException();
} catch (NumberFormatException ignored) {}

String[] numbers = text.split("[,:]");
return sumNumbers(numbers);
}
}
Copy link

Choose a reason for hiding this comment

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

메소드가 너무 많은 일을 하지 않도록 분리하기 위해 노력해 본다. 의 요구사항을 지키기 위해 메서드를 분리해보는건 어떨까요? 🤔

String[] 문자열_구분자로_분할()
int[] 문자열에서_숫자변환()
int 숫자전부더하기()

크게 위와 같이 기능을 분리할 수 있을것 같아요!

Copy link
Author

Choose a reason for hiding this comment

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

큰 차이가 있을까 싶었는데 말씀하신 것처럼 분리하니까 훨씬 깔끔하네요! 감사합니다.
혹시 더 개선할 부분이 있으면 말씀해주세요.


private static int sumNumbers(String[] numbers) {
int sum = 0;
try {
for (String number : numbers) {
int parsed = Integer.parseInt(number);
if (parsed < 0)
throw new RuntimeException();
sum += Integer.parseInt(number);
}
} catch (NumberFormatException ignored) {}
return sum;
}
}
51 changes: 51 additions & 0 deletions src/test/java/StringAddCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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_custom_구분자_negative() throws Exception {
assertThatThrownBy(() -> StringAddCalculator.splitAndSum("//;\n-1;2;3"))
.isInstanceOf(RuntimeException.class);
}
Comment on lines +40 to +50
Copy link

Choose a reason for hiding this comment

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

문자열 계산기에 숫자 이외의 값 또는 음수를 전달하는 경우 RuntimeException 예외를 throw한다.
음수값을 검증하는 테스트코드는 잘 만들어주셨는데, 숫자 이외의 값을 테스트코드가 없네요 😅
TDD 과정이니 요구사항을 만족하는 테스트코드를 먼저 작성한뒤 기능을 구현해보시는것 추천드립니다! :)

Copy link
Author

Choose a reason for hiding this comment

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

앗 그러네요; 다음 단계에선 더 신경써보겠습니다. 감사합니다!

}