why this code
"name".equals(person.getName());
is better than
person.getName().equals("name");
why this code
"name".equals(person.getName());
is better than
person.getName().equals("name");
I prefer the Yoda Expression "name".equals(person.getName());
since it means you don't need to check if person.getName()
is null
. That saves a bit of typing and is arguably clearer once you get used to it.
Although in your case, you'll still need to check if person
is not null
.
Because the constant "name"
can never be null
.
"name".equals(null)
is valid and will return false, whereas
String personName = null;
personName.equals("name");
will throw a NullPointerException
"name".equals(person.getName());
This code will avoid Null pointer exception.