0

I created Android application and run static analysis tool PMD on it. And what I don't get is why it is giving me warning and says to declare fields final when possible like in this example.

final City selectedItem = (City) arg0.getItemAtPosition(arg2);
new RequestSender(aaa).execute(xxx, selectedItem.getId());

It just starts inner AsyncTask instance. Is it good style to declare it final and why? For the sake of readability, I created a new object, but PMD says it should be final.

Bobans
  • 439
  • 6
  • 13
  • Is there a reason to store the instance of `RequestSender` in a property? Why not just `new RequestSender(aaa).execute(xxx,yyy);` – Phix Mar 07 '13 at 08:16
  • yes, you are right. thanks! But that was just example, so I will update my question. – Bobans Mar 07 '13 at 08:18
  • I gave a -1 because *static* and *final* are different. Pick the correct word and also use it in the title. But *better*, search first, like: `[java] why make variable final`. –  Mar 07 '13 at 08:20
  • Oh, I am sorry, it was silly mistake. I know the difference. – Bobans Mar 07 '13 at 08:22

1 Answers1

1

There are two different things here (you are talking both about static and final).

Regarding final, if you create a reference that you will not change (the object itself can be modified), it is a good practice to declare it final, for two reasons :

  • It helps the compiler to be able to do small performance optimizations
  • It helps you (or your fellow developer) to understand that this reference will not be changed - it gives a signal.

Regarding static (for a variable, the keyword has different meaning for different kind of structures), it would make your cityItems unique for all objects of its enclosing class. If all objects can use the same value, there is no gain to duplicate it. Again, think not only about the compiler/performance aspect, but also about the signal : if I see a field with "static", I know it is shared among all objects - I do not need additional info or documentation.

In your example, the field should probably be either public static (if it is shared) or private (public or "package protected" fields are breaking encapsulation).

Community
  • 1
  • 1
Martin
  • 7,634
  • 1
  • 20
  • 23