0

I am looking at a very old code-base, and every field access follows this pattern:

void method() {
  TYPE fieldRef = this.field;
  // Use fieldRef instead of field
}

I can't figure out why this pattern is followed rigorously. Is there some performance benefit to this? Does it have something to do with how fields behave with inheritance?

apxcode
  • 7,696
  • 7
  • 30
  • 41
HRJ
  • 17,079
  • 11
  • 56
  • 80
  • 2
    Is there some multi-threading going on? – Boris the Spider May 17 '14 at 18:24
  • @BoristheSpider Yes, there is multi-threading. And I can see how following this style of code could reduce inconsistencies. I will check the code once again, to see if that's why they are doing it this way. – HRJ May 17 '14 at 18:32
  • @user1803551 That other question is a little different. I know when I should use this. But in this code-base, *every* field access is using `this`. – HRJ May 17 '14 at 18:39
  • I found a more relevant duplicate. Since I can't delete this question, I am voting my own question be closed as duplicate. – HRJ May 17 '14 at 18:45

2 Answers2

0

this always refers the current class variables in the scenario you mentioned

so the benefit is just that the purpose of assigning value is satisfied the way it should be

Is there some performance benefit to this?

No its not for performance improvement

Does it have something to do with how fields behave with inheritance?

only if your parent class variables have same names Yes, or it does not have any thing to do with Inheritance as well

EDIT:

// Use fieldRef instead of field

this we usually do because in java if your field is an Object, it maintains reference and any modifications we do gets reflected in original object property.

dev2d
  • 4,245
  • 3
  • 31
  • 54
0

Maybe the coder wants to catch the instance object that this.field refers to with a temporary reference and immediately assign a different instance object to this.field.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417