티스토리 뷰

검출 메시지 

The type of the "map" object should be an interface such as "Map" rather than the implementation "HashMap".

List, Set, Map 사용 시 자주 실수하는 내용 중 하나입니다. 

심지어 List가 인터페이스인 줄도 모르는 개발자가 많습니다. 

왜 인터페이스를 사용해야 하는지를 모르면서 습관처럼 만들고 사용합니다. 

왜 그러해야하는가에 대한 것을 공부하고 좋은 습관을 만드는게 중요한거 같습니다. 


잘못 사용 되는 예

ArrayList<String> list = new ArrayList<>();

HashMap<String, String> map = new HashMap<>();

HashSet<String> set = new HashSet<>();


public void test(HashMap<String, String>){

    ...

}

수정 

List<String> list = new ArrayList<>();

Map<String, String> map = new HashMap<>();

Set<String> set = new HashSet<>();


public void test(Map<String, String>){

    ...

}

Declarations should use Java collection interfaces such as "List" rather than specific implementation classes such as "LinkedList" (squid:S1319)

CODE_SMELL Code smell MINOR Minor

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>(); 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;
  }
}


댓글
댓글쓰기 폼