3

why this code

"name".equals(person.getName());

is better than

person.getName().equals("name");
rennajihi
  • 443
  • 1
  • 6
  • 17
  • 3
    `"name"` will never be null – zec Apr 08 '16 at 14:17
  • 2
    `person.getName()` might return `null` however whether ignoring a `null` value is better than throwing an exception is debatable. – Peter Lawrey Apr 08 '16 at 14:18
  • #2 has a problems: person and `getName` are liable to return null. At a minimum, you need to include a null check for both person and getName() (unless you have some other mechanism that guarantees the latter will never be null – kolossus Apr 08 '16 at 14:23

3 Answers3

11

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

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

Darth Android
  • 3,437
  • 18
  • 19
1
"name".equals(person.getName());

This code will avoid Null pointer exception.

Krishnanunni P V
  • 689
  • 5
  • 18
  • 32