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.

1
  • 1
    It might be a weird optimization, see my answer here. Note I have no experience with Android. Commented Jul 23, 2011 at 17:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.