Java duplicated string literals

I feel that the rule “String literals should not be duplicated” - Rules explorer - should ignore String literals if the literals are commonly used and converting them to constants would make the code less readable.

For example look that the code below:

if ("checkbox".equalsIgnoreCase(tagNode.getAttributeByName("type"))) {
 if ("checked".equalsIgnoreCase(tagNode.getAttributeByName("checked"))) {
		matching.append(tagNode.getAttributeByName("name");
	} else {
		matching.append(tagNode.getAttributeByName("name");
	}
}

if ("radio".equalsIgnoreCase(tagNode.getAttributeByName("type"))) {
	if ("checked".equalsIgnoreCase(tagNode.getAttributeByName("checked"))) {
		matching.append(tagNode.getAttributeByName("name");
	}
}

The string literals such as “name”, “checked”, “type”, etc are all HTML element identifiers. So there is no need for Sonar to flag them as duplicate strings if they occur more than once in the class or project.

Hello @Sam2020 ,

We actually believe the opposite, hence the rule.
If you are going to reuse "name", "checked", "type" and all html-related names all over a class, file (or set of files), let’s minimize as much as possible the probability to do a typo somewhere, time to debug and find it, and use constants everywhere! This should drastically reduce the chances of doing the wrong thing, and I do believe that using constant is even, if not more, readable. Not even counting the fact that you could retrieve in an easier way every place where you manipulate “radio” buttons by following constant usages.

private static final String TYPE = "type";
private static final String CHECKBOX = "checkbox";
private static final String CHECKED = "checked";
private static final String NAME = "name";
private static final String RADIO = "radio";

...

if (CHECKBOX.equalsIgnoreCase(tagNode.getAttributeByName(TYPE))) {
    if (CHECKED.equalsIgnoreCase(tagNode.getAttributeByName(CHECKED))) {
		matching.append(tagNode.getAttributeByName(NAME);
	} else {
		matching.append(tagNode.getAttributeByName(NAME);
	}
}

if (RADIO.equalsIgnoreCase(tagNode.getAttributeByName(TYPE))) {
	if (CHECKED.equalsIgnoreCase(tagNode.getAttributeByName(CHECKED)) {
		matching.append(tagNode.getAttributeByName(NAME);
	}
}

Of course, if you still believe these issues should not be reported in your particular cases, feel free to ignore the issues raised by this rule on the concerned files, disable completely the rule or use the @SuppressWarnings("java:S1192") annotation. On our side, we don’t see the benefit of allowing some words, and will not change its implementation.

Cheers,
Michael

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.