본문 바로가기
Java

일급 컬렉션 (First-Class Collection) 이란?

by Mong-_- 2023. 10. 13.

전에 동기가 "일급 컬렉션이 뭐야?"라는 질문을 했다.

나는 당당히 모른다고 했고, 찾아보니 중요한 개념이었기에 정리를 하려고 체크리스트에 작성해 놓았었다.

 

체크리스트를 하나둘 격파하던 어느 날, 체크리스트.peek() == "일급 컬렉션 정리"가 되어서 정리해 보려 한다!

 

일급 컬렉션 너 나와!

땡 땡 땡~!


일급 컬렉션 (First-Class Collection)이란?

Collection을 Wrapping 하면서, 그 외 다른 멤버 변수가 없는 상태를 말한다!

 

일급 컬렉션을 사용하지 않은 예제를 보자.

public class Person {
	private List<String> todoList;

	public Person(List<String> todoList) {
		this.todoList = todoList;
	}
}

//Main
Person person = new Person(todoList);

 

Person 클래스가 List 타입의 todoList를 직접 다루고 있으므로 Person 클래스는 List 타입의 의존성을 갖게 된다.

추후 todoList의 구조가 변경될 때 Person 클래스도 같이 변경해 줘야 하는 문제점이 있다.

 

 

이제 일급 컬렉션을 사용해 보자.

public class Person {

	private TodoList todoList;

	public Person(TodoList todoList) {
		this.todoList = todoList;
	}
}

public class TodoList {

	private List<String> todoList;

	public TodoList(List<String> todoList) {
		this.todoList = todoList;
	}
}

//Main
Person person = new Person(todoList);

차이가 보이는가?!

기존의 Person 클래스는 todoList를 List 타입으로 관리하였지만, TodoList 클래스로 관리함으로써 List 타입의

의존성이 제거되고 TodoList 클래스와의 의존성만 갖게 되었다.

 

이런 의문이 들 수 있다.

"List 타입과 의존성을 제거하고 일급 컬렉션과의 의존성을 갖게 되었는데 무슨 의미가 있지?"

 

Collection을 Wrapping 함으로써 얻는 이점은 다음과 같다.

  • 비지니스에 종속적인 자료구조
  • Collection의 불변성을 보장
  • 이름이 있는 컬렉션

각각의 이점을 살펴보자.

- 비지니스에 종속적인 자료구조

TodoList 값에 대한 검증 로직이 추가 된다면, 코드들이 어떻게 변경되는지 살펴보자

 

일급 컬렉션을 사용하지 않은 코드이다.

public class Person {
	private List<String> todoList;

	public Person(List<String> todoList) {
		this.todoList = todoList;

		validateTotoList(todoList);
	}

	private void validateTotoList(List<String> todoList) {
		// 검증 로직
	}
}

Person 클래스가 TodoList와 관련된 로직을 모두 관리하고 있다. 이처럼 설계된 경우, TodoList에 대한 새로운 검증 로직이 생길 때마다 Person 클래스를 직접 변경해야 한다.

 

다음은 일급 컬렉션을 사용한 코드이다.

public class Person {
	private TodoList todoList;

	public Person(TodoList todoList) {
		this.todoList = todoList;
	}
}

public class TodoList {

	private List<String> todoList;

	public TodoList(List<String> todoList) {
		this.todoList = todoList;

		validateTotoList(todoList);
	}

	private void validateTotoList(List<String> todoList) {
		// 검증 로직
	}
}

Person 클래스는 TodoList에 대한 검증을 하지 않아도 되며, 검증 로직이 추가 되어도 TodoList 클래스의 코드만

수정하면 된다.

 

- Collection의 불변성을 보장

일급 컬렉션을 사용하여 해당 컬렉션을 불변(immutable)으로 만들어서 변경을 방지할 수 있다.

public class Person {
	private final TodoList todoList;

	public Person(TodoList todoList) {
		this.todoList = todoList;
	}

	public TodoList geTodoList() {
		return todoList;
	}
}

public class TodoList {

	private final List<String> todoList;

	public TodoList(List<String> todoList) {
		validateTotoList(todoList);

		this.todoList = Collections.unmodifiableList(new ArrayList<>(todoList));
	}

	// 로직
}

Collections.unmodifiableList()를 사용하여 불변 리스트로 변환하여, TodoList 객체를 생성한 후에는 List 컬렉션을 변경할 수 없다.

 

- 이름 있는 컬렉션

// 기존 컬렉션
List<String> todoList;

// 일급 컬렉션
TodoList todoList;

의미가 있는 이름으로 관리하기 때문에 컬렉션의 역할과 의미를 바로 파악할 수 있다.

 


 

끗!