-
[Refactoring] 13. 반복문클린코드 2022. 9. 16. 19:25
| 인프런 - 백기선님의 코딩으로 학습하는 리팩토링 강의를 수강하며 정리한 글입니다.
반복문
- 반복문에 비해 함수형 프로그래밍이라는 더 나은 대안이 생겼다.
- 반복문을 파이프라인으로 바꾸는 리팩토링을 거치면 필터나 맵핑과 같은 파이프라인 기능을 사용해 보다 빠르게 어떤 작업을 하는지 파악할 수 있다.
Refactoring 33. 반복문을 파이프라인으로 바꾸기
- 고전적인 반복문을 파이프라인 오퍼레이션을 사용해 표현하면 코드를 더 명확하게 만들 수 있다.
Before
public class Author { private String company; private String twitterHandle; public Author(String company, String twitterHandle) { this.company = company; this.twitterHandle = twitterHandle; } 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; } }
After
public class Author { private String company; private String twitterHandle; public Author(String company, String twitterHandle) { this.company = company; this.twitterHandle = twitterHandle; } static public List<String> TwitterHandles(List<Author> authors, String company) { List<String> result = authors.stream() .filter(author -> author.company.equals(company)) .map(author -> author.twitterHandle) .filter(twitterHandle -> twitterHandle != null) .collect(Collectors.toList()); return result; } }
=> 훨씬 이해하기 쉽고 간결하다.
'클린코드' 카테고리의 다른 글
[Refactoring] 15. 추측성 일반화 (0) 2022.09.18 [Refactoring] 14. 성의없는 요소 (0) 2022.09.17 [Refactoring] 12. 반복되는 switch 문 (0) 2022.09.15 [Refactoring] 11. 기본형 집착 (0) 2022.09.14 [Refactoring] 10. 데이터 뭉치 (0) 2022.09.13