Violation of PMD for each cycle (final or not?)

I recently learned about PMD and want to improve my code. So I turned on all the rules (and got 47,000 violations: P). Anyway, I have a problem with this:

double mean = 0; for (int p : points) mean += full[1][p]; mean /= points.size(); 

In a for each loop, PMD tells me that the local variable 'p' can be declared final . If I change it to

 double mean = 0; for (final int p : points) mean += full[1][p]; mean /= points.size(); 

he tells me Avoid using finite local variables, turn them into fields . The second violation does not make sense to me. What is the β€œright” way to do this? (I understand that there can be different ways, I just want to know how PMD will like it.)

+4
source share
2 answers

I think you find inconsistency in the pmd rules when one of the rules forces you to break the other rule.

I think the first loop is fine as it is: the second loop works fine, but using final , there is a rather unorthodox one. Adding final there for no good reason + can cause even very experienced developers. Since you do not want your program to be harder to read, I would recommend skipping final in foreach loops.

<h / "> + Providing a loop variable for an anonymous class is one such important reason.

+4
source

Save the last keyword inside the for loop. This will allow people to reassign the loop variable.

To get around "Avoid using finite local variables, turn them into fields" in

double vStd = 0; , given that you have not reassigned its value, you can declare it as a class constant.

In addition, declare each variable on a separate line:

 double vStd = 0; double mean = 0; 
0
source

Source: https://habr.com/ru/post/1480906/


All Articles