!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......
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.
Unfortunately, it's easy to accidentally use == to compare strings, but it will not work reliably. Remember: use equals() to compare strings. There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences.
In C, you can compare single characters (chars) by using the comparion operator ==, however, this method is not valid for comparing arrays of chars, or strings. Instead, you must use a function that compares each of the chars within the arrays in turn.
Now how we will check whether the string is a literal or an object. For this, we will be using the typeof operator. The typeof operator returns the type of any data type in JavaScript and returns their actual data type. Operands can either be literals or data structures such as variables, functions, or objects.
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
.
You shouldn't surround a blank string with quotes. ("").equals(!mapData.get("CON_PTY_PARTY_ID"))
should just be
! ("".equals(mapData.get("CON_PTY_PARTY_ID")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With