포스트

사소하지만 스프링 프로젝트에 기여해 본 경험

간단한 프로젝트를 하다가 처음으로 REST Docs를 도입하게 되었습니다. 아무래도 처음 쓰는 기술이다 보니, 내부 구현체를 직접 확인해가며 동작 흐름을 이해하려고 노력했습니다.

그러다가 다음과 같은 코드를 발견하게 되었습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private String modify(String input) {
  List < String > replacements = Arrays.asList(this.scheme, this.host, StringUtils.hasText(this.port) ? ":" + this.port: this.port);

  int previous = 0;

  Matcher matcher = SCHEME_HOST_PORT_PATTERN.matcher(input);
  StringBuilder builder = new StringBuilder();
  while (matcher.find()) {
    for (int i = 1; i <= matcher.groupCount(); i++) {
      if (matcher.start(i) >= 0) {
        builder.append(input.substring(previous, matcher.start(i)));
      }
      if (matcher.start(i) >= 0) {
        previous = matcher.end(i);
      }
      builder.append(getReplacement(matcher.group(i), replacements.get(i - 1)));
    }
  }

  if (previous < input.length()) {
    builder.append(input.substring(previous));
  }
  return builder.toString();
}

여기서 11번 라인을 봅시다.

1
builder.append(input.substring(previous, matcher.start(i)));

기존 작성자는 substring을 사용하여 input 문자열의 일부를 가져온 후 builder에 추가하려 했습니다만, 별도의 substring 호출 없이 바로 append 메서드를 사용해도 됩니다.

StringBuilder 클래스의 append(CharSequence s, int start, int end) 메서드는 문자열의 일부분만을 추출하여 추가하는 기능을 제공합니다. 따라서 아래와 같이 코드를 변경할 수 있었습니다.

1
builder.append(input, previous, matcher.start(i));

해당 커밋을 통해 REST Docs의 Contributor가 될 수 있었습니다.

비록 엄청나게 작은 리팩터링이지만, 코드의 가독성과 유지보수성을 높이는 작은 변화가 누적되면서 더 나은 코드로 나아갈 수 있지 않을까요?

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

Comments powered by Disqus.