Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 839
Bhushan Avatar asked Jan 05 '23 13:01

Bhushan


1 Answers

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.");
}
like image 87
user3579815 Avatar answered Jan 08 '23 02:01

user3579815