jdk17 버전의 프로젝트 진행 중 SonarLint 플러그인에서 instanceof, type casting 하는 코드에서 Code Smell이 있다고 해서 알아보게 되었다.
이전에는 instanceof 연산자로 검사하는 대상이 클래스나 인터페이스 타입에만 가능했지만, Java16에서 패턴 매칭을 지원하도록 개선되어 instanceof 연산자의 오른쪽 피연산자로 클래스, 인터페이스뿐만 아니라 패턴도 사용 가능하게 되었다.
또한, 타입캐스팅도 (Type) 형태로 타입 캐스팅을 했었지만, Type 형태로도 가능하게 되었다.
// 이전 버전의 instanceof, type casting
if (value instanceof Integer) {
return Integer.toString((Integer) value);
} else if (value instanceof Double) {
return Double.toString((Double) value);
} else if (value instanceof Boolean) {
return Boolean.toString((Boolean) value);
}
// java 16 이후 버전
if (value instanceof Integer integerValue) {
return Integer.toString(integerValue);
} else if (value instanceof Double doubleValue) {
return Double.toString(doubleValue);
} else if (value instanceof Boolean booleanValue) {
return Boolean.toString(booleanValue);
}
java 16 이후 버전의 예시에서 Integer integerValue, Double doubleValue 형식으로 Type variableName 형식으로 바뀌었는데, 이 패턴은 value라는 variable이 해당 타입으로 캐스팅 가능한 경우 캐스팅된 결과를 variableName에 할당하게 된다.
if, else if 분기에서 variableName을 사용하여 타입 체크를 수행하고, 캐스팅 결과를 바로 사용할 수 있게 되면서 코드가 간결해지며 불필요한 타입캐스팅을 사용하지 않아도 되게 되었다.
끝
'Java' 카테고리의 다른 글
[Java] try-with-resources (0) | 2024.04.22 |
---|---|
[Java] TypeFactory으로 제네릭 타입 변환하기 (0) | 2023.11.01 |
[Java] 비어있는 리스트(Collections.emptyList()) (2) | 2023.10.31 |