Bhushan
Bhushan

Reputation: 1547

PMD : Avoid using Literals in Conditional Statements

I have following code. I am getting "Avoid using Literals in Conditional Statements." warning in PMD on line number 5.

List<Object> listObj = getData();
 if (listObj.isEmpty()) {
      throw new NoEntity("No entity found for given Device.");
 }
 if (listObj.size() > 1) {
      throw new MultiEntity(
          "Multiple entity record found for given Device.");
 }

I prefer not to put global static final int variable having value as 1 and use it in if condition. Any other solution for this ?

Upvotes: 6

Views: 9978

Answers (4)

user3579815
user3579815

Reputation: 572

You can insert an assignment before the conditional, with a nice variable name that will serve as documentation. You'll improve the readability and make the warning go away.

boolean multiEntityDevice = listObj.size() > 1;
if (multiEntityDevice) {
  throw new MultiEntity(
      "Multiple entity record found for given Device.");
}

Upvotes: 4

Linus Fernandes
Linus Fernandes

Reputation: 496

You can modify the rule definition in your PMD configuration to include 1 as a MagicNumber. I don't see any reason why 1 should not be one of the default values in the rule itself.


<rule ref="category/java/errorprone.xml/AvoidLiteralsInIfCondition">
    <properties>
        <property name="ignoreMagicNumbers" value="-1,0,1" />
        <property name="ignoreExpressions" value="true" />
    </properties>
</rule>

If you don't like having to modify the rule configuration yourself, you can raise an issue with PMD on Github.

Upvotes: 3

Csuki
Csuki

Reputation: 1366

The best solution is to suppress the warning is such simple cases with @SuppressWarnings("PMD.AvoidLiteralsInIfCondition").

However, for your example I have a solution.

Use Guava's Iterables:

List<Object> listObj = getData();
try {
    Object myObj = Iterables.getOnlyElement(listObj);
} catch (NoSuchElementException e) {
    // "No entity found for given Device."
} catch (IllegalArgumentException e) {
    // "Multiple entity record found for given Device."
}

Upvotes: 3

Dhananjay
Dhananjay

Reputation: 554

If you are using Apache Commons Lang, it's available in NumberUtils https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#INTEGER_ONE

Upvotes: 2

Related Questions