Java - Coding Style. What are the pros and cons of comparing strings of the "ABC" .equals ("SOMESTRING") style?

Let me start with a sample code first ...

String password = ""; if("PIRATE".equals(password)) { // Do something } 

See here, a constant or a literal String (independently). "PIRATE" is used to check if two lines are equal. While...

 String password = ""; if(password.equals("PIRATE")) { // Do something } 

it also works exactly the same as the previous code.

Currently, I see a lot of the first style β€œSTRING_LITERAL” .equals (STRING_OBJECT) , while Java people are posting code.

So my question is: Where does this style come from? And how much better is this than the second style?

In fact, I think the second style is more logical than the first, why ?!

allows you to fulfill the requirement, for example, if the password provided by the user is "PIRATE", and then give permission to this user

when you start to fulfill the above requirement,

 String userProvidedPassword = getPaswordFromUser(); if(userProvidedPassword.equals("PIRATE")) { // Allow him } 

Isn't this more logical than "PIRATE" .equals (userProvidedPassword); ?! Just think about it ...

Correct me if I am wrong .. Thanks ..


EDIT: Sorry, this question did not appear in my previous search, and it answers my question perfectly. Also thanks to everyone who helped here.

+6
source share
3 answers

When you write password.equals("PIRATE") , you almost ask for a NullPointerException , where there is a chance for password may null.

All about avoiding a NullPointerException .

 if("PIRATE".equals(password)) { // Do something } 

Avoids NullPointerException

where as

 if(password.equals("PIRATE")) { // Do something } 

thrwos you NullPointerException if password is null .

However, I personally feel that it looks weird in the middle of the code. and I always prefer to write

 if(password !=null && password.equals("PIRATE") ){ //do something } 
+8
source

"PIRATE".equals(password) cannot "PIRATE".equals(password) NullPointerException .

whereas

password.equals("PIRATE") will throw a NullPointerException if password is null .

Therefore, it is recommended to use the first: it is safer.

+16
source

The only conflict is really a style issue. The expression "PIRATE" .equals (password) is called the "Yoda State" . However, as people have already noted, it is safer to use this state (so I will continue to use this view).

+3
source

Source: https://habr.com/ru/post/950083/


All Articles