0
votes

I try to commit my code but the code analysis in IntelliJ shows: 'if' statement can be simpolified in this line:

if (legendTitle != null && legendTitle.equals("My house"))

legendTitle is a String, I wrote legendTitle != null because .equals in a null Strings is a NullPointerException

2
you could easier do that as this: if ( "My house".equals(legendTitle)) - Stultuske
That said, I probably wouldn't bother - the line is fine as is. At least that way it clearly communicates that the null case has been considered. - Hulk
If the legendTitle is the result of some method call, you could consider changing the return type of that method call to Optional<String> and use the appropriate Optional methods, but if it is something local, that would probably be unnecessary overhead. - Hulk
Do you even want to support the case that legendTitle is null? Because if you consider this a bug in your code you should actually trigger the exception on purpose, fail-fast. Otherwise you wont notice the bug. However, in that case prefer Objects.requireNonNull(legendTitle);, more expressive. - Zabuzard

2 Answers

6
votes

You can write if ("My house".equals(legendTitle)). "My house" can never be null so you won't get NullPointerException in this case.

1
votes

You could use if (Objects.equals(legendTitle, "My house")). The Objects class will handle null values correctly.