nebkat
nebkat

Reputation: 8575

Java Advantages of Converting Global Variables to Local Variables in Methods

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.

Upvotes: 4

Views: 4469

Answers (2)

AlexR
AlexR

Reputation: 115378

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

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().

Upvotes: 4

Related Questions