반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- AOP this
- vaultTemplate
- spring
- AOP
- JsonType
- RestTemplate
- Thread Safety
- JsonStringType
- Spring Boot
- Save Action
- fotmatter
- jpa
- AOP target
- LogInterceptor
- ClientHttpRequestInterceptor
- 포맷터
- Stream
- @AutoConfiguration
- auto configuration
- gradle
- Starter
- AOP 매개변수
- findAny
- 개방/폐쇄 원칙
- java
- ResponseBodyAdvice
- findFirst
- restTemple
- AccessLevel
- 쓰레드 안전
Archives
- Today
- Total
맨땅에 헤딩하는 개바른자
enum 비교 시 어떤게 좋을까? "equals" or "==" 본문
반응형
enum 의 비교문
코드리뷰를 진행하다가 enum관련 된 질문을 받게 되었다
enum 비교 시 문자열 비교 equals는 지양한다고 코멘트를 받았다
enum 값이기 때문에 동등비교 하시면 됩니다.(enum 을 문자열로 비교하는 것은 지양)
ex) AlarmApplicantBatchDto.AlarmApplicantDto.SendType.APP_PUSH == item.getSendType()
그리고 enum 비교를 위한 if/else 는 switch 문을 활용하면 깔끔해집니다.
- 왜?
차이점은 무엇 입니까 == / equals?
일반적으로 ==은(는) 실행 가능한 대안이 아닙니다 equals. 그러나 ( with 와 같은 enum) 경우 고려해야 할 두 가지 중요한 차이점이 있습니다.
== 비교는 NullPointerException을 절대 던지지 않는다
enum Color { BLACK, WHITE };Color nothing = null;
if (nothing == Color.BLACK); // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException
== 컴파일 타임에 유형 호환성 검사를 받습니다.
enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types!
- 다양한 자료를 찾아본 결과 결론적으로는 equals를 사용해도 동작에는 영향이 없지만 enum은 == 부등호로 비교한다.
- 컴파일과정에서 명확하게 타입 호환성을 체크 하기때문에 잘못 비교되는 일을 줄일 수 있다.
- npe 오류를 줄일 수 있다
반응형
'개발 TIP' 카테고리의 다른 글
CRUD 공통로직 만들기 (0) | 2022.05.10 |
---|---|
Request DTO Validate Aspect 적용기 (0) | 2022.05.10 |
restTemplate LogInterceptor (0) | 2022.05.03 |
MDC LogFilter 사용하기 (0) | 2022.05.02 |
restTemple 제네릭Type 사용 (0) | 2022.04.28 |