0

why the vast majority of examples of android declares the return variable as final in methods like findViewById(id)? For example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_enc_disp);

    final ListView listViewEncDisp = (ListView) findViewById(R.id.listViewEncDisp);
    listViewEncDisp.setOnItemClickListener(this);
}

I know that a final variable can not be assigned again, however do not understand why you need this good habit. Thanks in advance

iberck
  • 2,372
  • 5
  • 31
  • 41
  • related to http://stackoverflow.com/questions/266806/is-there-any-performance-reason-to-declare-method-parameters-final-in-java – ben75 Feb 07 '13 at 21:39

2 Answers2

1

Adding final blindly to all variables is not a good habit. It's common accepted practice to mark fields as final whenever possible. Making parameters and variables always final is more subjective. I personally avoid it as it just add to clutter. Also note that making a variables final has no runtime impact, for the most part it's purely a compile time constraint.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • "Also note that making a variables final has no runtime impact", counter argument may be if you don't make your arguments final and assign object to parameter variable with in method, changes will not reflect on original object and it happens very frequently with new developers (I agree with your "more subjective" answer as well as don't want lead to some other discussion, but thought to put as valid counter argument). – kosa Feb 07 '13 at 20:59
-1

If you do not want to change object, you should declare it as final, it is good practice to avoid random errors on compile time.

For example, you could try to assign another value in other place in code, just because you forget that you did it before, and then you could spend minutes, sometimes hours trying to find error.

Artem Zinnatullin
  • 4,305
  • 1
  • 29
  • 43
  • 1
    I fail to see how reassigning a variable unintentionally would cause "errors on compile time" – Steve Kuo Feb 07 '13 at 20:51
  • @SteveKuo `final int x = 7; ... ; x = 8;` where the second assignment is unintentional won't compile. So you avoid the error at compile time rather than later in testing. – Pete Kirkham Feb 07 '13 at 21:02
  • For example, you creating EditText and assigning it to R.id.edit_text1, then your collegue assigning EditText R.id.edit_text2 because he forget that you did it before, that is all, you can no longer work with EditText as you wanted before. – Artem Zinnatullin Feb 07 '13 at 21:02