Reputation: 59
I've just came across some code which is slightly strange, I was wondering if anyone could shed light on why it might be written like this.
I think it's got something to do with concurrency - so that the variables can't get changed if another thread accesses it (because variable updates aren't atomic). Or it's speed (because local variables are faster than class level variables?) OR I'm wrong on everything I've written here :)
Oh, I'm not talking about the Hungarian notation, I'm talking about the local assignments inside the methods.
public Class Space
{
private double m_dWidth = 0;
// Constructors & other methods omitted for readability
//...
public double getWidth()
{
double dWidth = m_dWidth;
return dWidth;
}
}
Upvotes: 3
Views: 162
Reputation: 328913
I can only think of two situations where copying an instance variable to a local variable can make sense:
if m_dWidth
is volatile or even final and you use it more than once in a method, taking a local copy may improve performance (with the risk of missing updates, which may be acceptable) - example in ArrayBlockingQueue#extract
:
final Object[] items = this.items;
in some complex concurrent constructs, such as String#hashcode
, where taking a local copy of a shared, non volatile, variable is necessary to ensure correctness in a multithreaded context:
int h = hash;
In the specific example you give, it makes no difference (apart from unnecessarily cluttering the code).
Upvotes: 2
Reputation: 11453
It should be written written without local variable. Local variable in getter is useless.
public double getWidth()
{
return m_dWidth;
}
Upvotes: 0
Reputation: 96016
This has nothing to do with any of what you've wrote. Think about this piece of code:
class MyClass {
private int myInt;
//...
public int getData() {
return myInt;
}
public int strangeGetData() {
int temp = myInt;
return temp;
}
public int strangeGetData2() {
int temp = myInt;
int temp2 = temp;
int temp3 = temp2;
return temp3;
}
}
When you use any of the getters, you'll get the same result. Note that myInt
is a member variable, it can be accessed anywhere inside the class.
I advise you to go through a tutorial to better understand this.
Upvotes: 0
Reputation: 1942
It looks like the person writing the code has misunderstood how return
works. It is a common misunderstanding among my java students (university first year) that return
only works on locally defined variables instead of arbitrary expressions.
As @Steve suggests, it could also be a hangover from an older, more complicated version of the code. Which one is more likely depends on where you found the code.
Upvotes: 3