!mapData.get("PARTY_ID").equals("") // <-- gives SonarQube error
In the above piece of code, I am getting "String literal expressions should be on the left side of an equals comparison" this error in Sonar. So how we can avoid it.
I tried this:
("").equals(!mapData.get("CON_PTY_PARTY_ID"))
But it does not work. Give some advice......
Others have pointed out that the way to avoid this error is to use:
! ("".equals(mapData.get("CON_PTY_PARTY_ID")))
But no one has pointed out why this matters. The reason the literal should be on the left side of the equals comparison is to avoid the possibility of an exception if the string being compared to it is null.
As written in the question, if the value of mapData.get("CON_PTY_PARTY_ID")
was null
, then the expression would be trying to invoke the equals(..)
method of an object that doesn't exist. That would throw an exception. By putting the literal on the left, then even if the value of mapData.get("CON_PTY_PARTY_ID")
was null
, the method "".equals(...)
would be defined and would not throw an exception. It would simply return false
.