Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Questions about string comparison

 
Azuritul Wu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone:

While I was reading other people's code...I found the following two coding styles...And I am a little bit curious that whether they differ only in style or some other areas?



 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first case, if the variable operation is null, you will get a NullPointerException, when the String is compared. But that won't be the case with the second style.

Additionaly, it is easy to change "doModify" to "doUpdate", if they are defined at a single place as given in the second approach.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first method will get a null pointer exception if the request attribute isn't present. Other than that, the second is generally preferred as it's clearer and easier to change later.
 
Azuritul Wu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help.
Now i know how to use it.

Thank you.
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The usage of Constants are pretty good, where there might be a need to change the actual value. As for the null value checking, I prefer checking the null value before doing actual operation on the variable. Otherwise, the unforgivable NullPointerException will occur.
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ko Ko Naing:
The usage of Constants are pretty good, where there might be a need to change the actual value. As for the null value checking, I prefer checking the null value before doing actual operation on the variable. Otherwise, the unforgivable NullPointerException will occur.


The point is that with the constant.equals() trick, you don't have to worry about the NullPointerException, because it won't happen. You know the constant String is non-null and the String class can compare itself to a null value and return false.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic