static import를 사용하면 static 메서드를 사용할 때나 이너 클래스를 사용할 때 클래스명을 생략할 수 있다. 잘 활용하면 테스트 코드를 작성할때 가독성을 올려준다거나 하는 이점도 있지만 패키지 구조를 다 아는 내 눈에만 예뻐 보일 수 있겠다는 생각이 들었다.

 

오히려 가독성을 떨어트리고 헷갈리게 할 수 있기 때문에 전역적으로 사용되고 static import를 해도 이해하기 쉬운 부분에 사용하는 것이 좋을 것 같다.

 

 

언제 사용하면 좋은지 해당 글에서 보았다.

 

Static Import

In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say: double r = Math.cos(Math.PI * theta); In order to get around this, people sometimes put static members into an interface and

docs.oracle.com

 

when should you use static import? Very sparingly! 

use it when you require frequent access to static members from one or two classes.

 

아주 드물게 사용해야 한다고 강조하고 있다!

 

If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability

대충 남용하면 가독성 떨어지고.. 유지 보수 어렵고.. 네임스페이스 오염시키고.. 코드 읽는 사람이 헷갈리고.. 등등 엄청 안좋다는 말

 

if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

 

이전에 혼자 코드 짤 때 static import 하는게 깔끔한거 같아서 막 다 static import를 했었는데 다른 분이 짠 코드를 보다보니 static import가 안 되어있는 것이 보기에 이해가 더 잘 됐다. 그래서 이거 사용하는거 맞나 의문이 들었는데 찾아보길 잘한 것 같다.

 

 

 

 

[참고]

 

[Java] Static import에 대한 관찰

JDK5에서 Static import가 추가되었다. 먼저 static import를 적용하지 않은 일반 코드를 보자. 가장 기본적인 용법은 import문 뒤에 static을 붙이고, {패키지.클래스.\*} 혹은 {패키지.클래스.멤버} 를 적으면

velog.io

 

+ Recent posts