Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables: Programming Practices

Tags:

java

methods

Given the following methods:

public int methodOne() {
    int total = local_int_one + local_int_two;
    return total;
}

public int methodTwo() {
    return local_int_one + local_int_two;
}

1) Is the only difference in the above methods readability or is there a micro-optimization "benefit" in methodTwo()?

2) Should the defining of local variables in a narrow scope be shunned and avoided when possible? (I can see methodTwo becoming unreadable if several calculations must be performed in a single statement)

like image 325
VILLAIN bryan Avatar asked Oct 03 '15 20:10

VILLAIN bryan


People also ask

Why is it good practice to use local variables?

So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.

What are local variables examples?

For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.

What are the 4 types of variables in coding?

Constants, global variables, class variables, instance variables, and local variables.

What does local variable mean in coding?

A local variable is a type of variable that can be used where the scope and extent of the variable is within the method or statement block in which it is declared. It is used as an iteration variable in the foreach statement, exception variable in the specific-catch clause and resource variable in the using statement.


1 Answers

The short answer is: methodTwo() is slightly more efficient.

methodOne() results in the following bytecode:

public int methodOne();
 0  aload_0 [this]
 1  getfield com.example.Test.local_int_one : int [13]
 4  aload_0 [this]
 5  getfield com.example.Test.local_int_two : int [15]
 8  iadd
 9  istore_1 [total]
10  iload_1 [total]
11  ireturn

And here's the bytecode for methodTwo():

public int methodTwo();
 0  aload_0 [this]
 1  getfield com.example.Test.local_int_one : int [13]
 4  aload_0 [this]
 5  getfield com.example.Test.local_int_two : int [15]
 8  iadd
 9  ireturn

But note that this optimization is too minor, and that code readability in this case matters a lot more then a couple of java instructions.

If you think a temporary variable will contribute to code readability, then, by all means, use it.

like image 74
Alex Shesterov Avatar answered Nov 10 '22 10:11

Alex Shesterov