I just was tidying my code a bit and there was this piece:
String saving = getValue();
if(saving != null && saving.equals(\"true\")){
// do someth
if ("true".equals(saving))
is perfectly "save" and recommended by dummy product as SonarLint and any other advisors that establish this "well" thinked rule that your chief request that you follow.
I say stupid and my explanation is the following.
What happens if you have following code
if (!saving.equals("true"))
{
if (saving.length() > 10)
{
// do something
}
}
You can use following advised code
if (!"true".equals(saving))
{
if (saving.length() > 10)
{
// do something
}
}
But when your code is deployed on production, the program will crash on length() function if saving variable has not been initialized and contains NULL.
You have changing your code to avoid NullPointerException on equals() function but your program will return another NullPointerException on length() function !
The good reaction is to stop to use String literal tip and to analyze code to find a perfect solution as in the following example.
if (saving != null)
{
if (!saving.equals("true"))
{
if (saving.length() > 10)
{
// do something
}
}
}
or
if (saving == null) saving = "";
if (!saving.equals("true"))
{
if (saving.length() > 10)
{
// do something
}
}
Is is perhaps verbose but if you will use Java for programming it is the price to pay.
Using String literal equals() method to avoid NullPointerException has the following disadvantages