tonykang22 / study

0 stars 0 forks source link

[Refactoring] 냄새 13. 반복문 #34

Open leeyuunsung opened 2 years ago

leeyuunsung commented 2 years ago

냄새 13. 반복문 (Loops)


리팩토링 33. 반복문을 파이프라인으로 바꾸기 (Replace Loop with Pipeline)

Before

static public List<String> TwitterHandles(List<Author> authors, String company) {
    var result = new ArrayList<String> ();
    for (Author a : authors) {
        if (a.company.equals(company)) {
            var handle = a.twitterHandle;
            if (handle != null)
                result.add(handle);
        }
    }
    return result;
}

After1(강의 예제)

static public List<String> TwitterHandles(List<Author> authors, String company) {
    return authors.stream()
                .filter(a -> a.company.equals(company))
                .map(a -> a.twitterHandle)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
}

After2

static public List<String> TwitterHandles(List<Author> authors, String company) {
    return authors.stream()
                .filter(a -> a.company.equals(company) && a.twitterHandle != null)
                .map(a -> a.twitterHandle)
                .collect(Collectors.toList());
}