4

I am working on an android launcher based on the stock launcher. I am just interested why are there lots of global variables converted to local variables in methods e.g.

final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000);

instead of just

mVelocityTracker.computeCurrentVelocity(1000);

Is it some android thing or a general java rule? It makes no sense allocating a new VelocityTracker when it can be accessed directly.

EDIT Yes this code is being repeated many times.

nebkat
  • 8,445
  • 9
  • 41
  • 60
  • 1
    It might be a weird optimization, see my answer [here](http://stackoverflow.com/questions/6602922/is-it-faster-to-access-final-local-variables-than-class-variables-in-java/6603067#6603067). Note I have no experience with Android. – Tomasz Nurkiewicz Jul 23 '11 at 17:16

2 Answers2

4

This can be useful if you are using a field many times. Some JVM and I assume Android VMs don't optimise access to fields as efficiently.

However it can be overused and I don't see the point if only accessed once.

It can also be useful of you are accessing a volatile field. This ensures when you use that field many times you are taking about the same object. e.g.

volatile String text;

String text = this.text;
if(text != null)
    doSomething(text);

If you didn't use a local variable text could be non-null for the if statement and null for the doSomething().

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

You are right, in your short example this assignment does not have any sense. But generally it is a good practice to minimize scope of variables. This allows you to concentrate on specific code that deals with specific variables.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • 1
    How is it ever useful to assign a field to a local variable when the field is just as accessible as the variable? How does this "minimize the scope of variables"? – Kirk Woll Jul 23 '11 at 17:23