티스토리 뷰

String equals() 메소드를 사용하면서 늘 


variable.equals("string value"); 형태로 사용해왔다.


그러던 중 다른 사람의 모듈을 수정해야할 일이 생겨 로직을 분석하던 중 


JSON 특정 필드의 빈값 체크를 하는 코드에서 


"".equals(variable) 형태를 자주 사용하는 것을 보게되었고 


그 둘의 차이가 궁금해졌다.



후자의 경우 NullPointerException 위험을 배제할 수 있다고 머릿속에 좀 두루뭉실하게 알고 있어서 여기 저기 찾아보다가 


이해가 한방에 되는 Stackoverflow 형님의 글을 발견하게 되었다. 


나와 같은 문제를 앓고 있던 개발자였나보다




Java : “xx”.equals(variable) better than variable.equals(“xx”) , TRUE?

Java : "xx"equals(variable) 이 varibale.equals("xx") 보다 좋은게 실화냐?


답변 

This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.

  • I definitely think it is something that all Java programmers should be aware of as it is a common idiom.
  • It's also a useful technique to make code more concise (you can handle the null and not null case at the same time).

But:

  • It makes your code harder to read: "If blue is the sky..."
  • If you have just checked that your argument is not null on the previous line then it is unnecessary.
  • If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.

Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.


전자의 경우 간결한 처리방법이 될 수 있으며 null 이나 not null 경우를 동시에 처리할 수도 있는 좋은 방법이지만 

코드 읽기를 힘들게 할 수 있고 이미 null 체크를 앞에서 한 경우에는 불필요한 코드가 될 것이다.

그리고 NullPointerException 을 빠르게 발견하지 못할 수 있다는 것. 


요약을 하자면 어쨌든 둘다 case-by-case 라는 듯...

나는 후자를 선호한다. 


'프로그래밍 > Java' 카테고리의 다른 글

[Jackson] JSON Serialization Error  (1) 2017.02.20
Directory 만들기  (0) 2014.10.21
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함