일급 컬렉션 (First Class Collection)은 객체지향 생활체조에서 처음 언급되었다.
public class PostList {
private Map<Long, PostDto> posts;
public PostList(Map<Long, PostDto> posts) {
this.posts = posts;
}
}
@Test
void 파이널키워드() {
final Map<Long, String> map = new HashMap<>();
map.put(1L, "이건");
map.put(2L, "몰랐지");
Assertions.assertThat(map.size()).isEqualTo(2);
}
따라서 재할당이 아닌 불변 Collection을 만들고 싶으면 일급 컬렉션을 생성 한 뒤, 변경 메서드를 만들지 않는 방법을 사용하자.public class PostList {
private Map<Long, PostDto> posts;
public PostList (Map<Long, PostDto> posts) {
this.posts = posts;
}
public Long javaPostListMethod() {
return posts.stream()
.filter(post -> post.getCategory().equals(JAVA))
.sum();
}
public void pythonPostListMethod() {
어쩌구 저쩌구 로직
}
public void goPostListMethod() {
어쩌구 저쩌구 로직
}
}
일급 컬렉션을 사용하지 않는 경우에는 Map<Long, PostDto> posts = new HashMap<>();
posts.put(1L, "이건");
posts.put(2L, "몰랐지");
Long size = posts.stream()
.filter(post -> post.getCategory().equals(JAVA))
.sum();
;
이와 같이 map과 메서드의 관계가 코드에서 전혀 표현되지 않는다. 그리고 post의 카테고리에 따른 계산을 강제할 수 없다. 수정이 필요할 때 관련 메서드를 찾아서 수정해야 한다.//1번
Map<Long, PostDto> posts = ~~~
//2번
PostList posts = ~~~
JavaPostList javaPosts = ~~~
PythonPostList pythonPosts = ~~~
1번과 달리 2번은 명확한 표현으로 posts를 나타낼 수 있다. 명확한 표현을 사용하기 때문에 검색에도 용이하다.참고