List, Set, Map을 사용하다보면 습관적으로 List 리스트= new ArrayList처럼 사용하게 된다.
하지만 구현체를 직접 선언하여 ArrayList 리스트 = new ArrayList로 사용하게된다면 다음과 같은 린트(Lint) 메시지를 확인 할 수 있다.
Declarations should use Java collection interfaces such as "List" rather than specific implementation classes such as "LinkedList"
The purpose of the Java Collections API is to provide a well defined hierarchy of interfaces in order to hide implementation details.
Implementing classes must be used to instantiate new collections, but the result of an instantiation should ideally be stored in a variable whose type is a Java Collection interface.
This rule raises an issue when an implementation class:
- is returned from a public method.
- is accepted as an argument to a public method.
- is exposed as a public member.
Noncompliant Code Example
public class Employees {
private HashSet<Employee> employees = new HashSet<Employee>(); // Noncompliant - "employees" should have type "Set" rather than "HashSet"
public HashSet<Employee> getEmployees() { // Noncompliant
return employees;
}
}
Compliant Solution
public class Employees {
private Set<Employee> employees = new HashSet<Employee>(); // Compliant
public Set<Employee> getEmployees() { // Compliant
return employees;
}
}
먼저 List, Set, Map은 Interface이다.
그리고 각각의 구현체로는 ArrayList, LinkedList, HashSet, HashMap 등등 존재한다.
왜 굳이 구현체로 선언하지않고 Interface로 업캐스팅할까?
다형성을 지원하기 위해서이다.
유연한 구조로 설계하여서 나중에 다른 구현체로 변경할때 쉽게 변경하기 위해서 사용한다.
즉 업캐스팅으로 선언하면 모든 코드가 해당 Interface를 따르게 코드를 작성할 수 있고, 해당 Interface를 구현한 다른 자료형 간 쉽게 변경이 된다.
잘못 사용된 예
//구현체를 직접 사용하는 경우
ArrayList<String> list = new ArrayList<>();
HashMap<String,Object> map = new HahMap<>();
HashSet<String> set = new HashSet<>();
public void methodName(HashMap<String,Object> param){
....
}
올바른 예
//Interface로 업캐스팅하여 사용하는 경우
List<String> list = new ArrayList<>();
Map<String,Object> map = new HahMap<>();
Set<String> set = new HashSet<>();
public void methodName(Map<String,Object> param){
....
}
참고
Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?
Possible Duplicate: Why should the interface for a Java class be prefered? When should I use List<Object> list = new ArrayList<Object>(); ArrayList inherits from List, so if some
stackoverflow.com
'개발 이야기 > Java' 카테고리의 다른 글
[Effective Java-ITEM 2] Builder (0) | 2022.09.26 |
---|---|
[Effective Java-ITEM 1] 정적 팩토리 메소드 (0) | 2022.09.15 |
Try-With-Resources를 이용한 자원 반납 (0) | 2022.05.25 |
강한 결합과 약한 결합 (0) | 2022.05.18 |