• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Convention for instance variables

 
Greenhorn
Posts: 22
2
IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everyone,

I'm learning java, and there's one small but nagging question in my mind about instance variables. I understand that when calling an instance variable inside its class, I can use either "variableName" or "this.variableName". Most of the time both will work and "this" is only necessary if there is a local variable with the exact same name as the instance variable. So far, so good.

But what is the best practice? Should I always use "this.variableName" so it's obvious that it's an instance variable? Or only when it's necessary because a local variable has the same name? Or does it not matter which?

And by the way, is using the same name for an instance variable and a local variable something that should never ever happen, or is it ok sometimes?
For example would this be fine, or should the variables have different names:

 
Saloon Keeper
Posts: 10705
86
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IMHO. I think "this" should not be used unless there is a name conflict. It makes the code harder to read. So, should you always avoid a name conflict? I think a name conflict is not bad in certain situations but should be avoided otherwise. My feeling is that if the method or constructor is relatively small and there is a synonymous relationship between the instance variable and a parameter, then it is ok and perhaps even useful as it highlights the tight coupling. YMMV.
 
Marshal
Posts: 8857
637
Mac OS X VI Editor BSD Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch, Aline.

Nicely constructed question, and even better provided answer by yourself

Without expanding a lot, in most cases you'll see the common practice to have same names in constructor, so 'this' keyword is necessarily and needs to be used.
However, to use 'this' keyword everywhere else for each instance variable isn't necessarily, and in fact probably shouldn't (even though it is safer to use), as that would unecessarily overload class with redundant code.

And what you pointed out yourself, in other cases than constructor, to introduce variables with the same name as instance - isn't good practice, so should be avoided in most cases as it is error-prone.

Have a cow for a great question.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great question. And welcome to the Ranch!

This isn't a recommendation but rather a summary of the rules of thumb that I use to guide my own practice. So basically, my $0.02.

My primary considerations, in order of importance, are:

1. Clear and unambiguous - the reader should have little to no reason to do a double take or doubt what the scope of a variable is
2. Idiomatic - the usage should be something that someone with at least some experience would easily recognize and understand immediately
3. Succinct / brief - no redundancy
4. Consistent - with any code standards or conventions that the team has agreed upon

For example, in setters, this.myField = myField is idiomatic and leaves very little doubt as to the necessity of the this keyword. However, small getters that directly access a field don't need this and I see little value in using it when doing so can be done without ambiguity or hit to clarity. So, I tend to leave it out in my getters. However, if there is an agree-upon coding standard that requires them even when they are redundant, I just go with the flow if I cannot get the standard modified to my liking or if it's too prevalent in the code base. I usually take the path of least resistance with a bias for my preference for succinctness.

Having a same-named local variable is definitely something I avoid if the usage is not idiomatic and could compromise clarity and consistency. It's easy to avoid or fix by Refactor-Rename.
 
Marshal
Posts: 79177
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Agree with Junilu. In the instance you describe, something like
this.name = name;
is probably the best style because it allows you to use the field name which you spent hours refining as a parameter name where everybody can see it. The same applies to constructor parameters.
Note that simple use of the = operator is acceptable if the variable is a primitive or an immutable type; if it is a mutable reference type it should be copied before you let it into your object and copied before you let it out of your object. This is a sample section from the old edition of Joshua Bloch's Effective Jaca™ about copying fields.
 
Aline Galea
Greenhorn
Posts: 22
2
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you all for the welcome and the answers (and the cow    )

Campbell Ritchie wrote:Note that simple use of the = operator is acceptable if the variable is a primitive or an immutable type; if it is a mutable reference type it should be copied before you let it into your object and copied before you let it out of your object. This is a sample section from the old edition of Joshua Bloch's Effective Jaca™ about copying fields.


Huh. I never really thought about what using reference variables meant for encapsulation. Thanks for that too.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Aline Galea wrote:. . .  I never really thought about what using reference variables meant for encapsulation. Thanks for that too.

Lots of people don't realise that for a very long time. And … “that's a pleasure
 
Saloon Keeper
Posts: 15510
363
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The use of 'this' inside constructors and setters has already been mentioned. Another place where I like to use the 'this' keyword is inside a method that takes as its argument another object of the same type. In those cases 'this' is used to explicitly show whether the current object or the external object is being acted upon. Examples include the equals() method and the compareTo() method:
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:. . . . use the 'this' keyword is inside a method that takes as its argument another object of the same type. In those cases 'this' is used to explicitly show whether the current object or the external object is being acted upon. . . . .

In that situation, this. is redundant.

Don't think that redundant means unnecessary. Think of it as meaning optional or additional. I agree it makes the intent of the method easier to understand.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Stephan illustrates another rule of thumb I follow: Expressiveness.  When I find the code is more expressive when a redundant this is used, I will prefer to use it.  

Expressiveness can often boil down to individual preference or even level of experience/sophistication so the question of whether or not to use this can essentially become one of form vs function, i.e. style. Personally, I find lines 38-39 in Stephan's example more expressive than if the redundant this had been left out.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . . redundant . . . .

Redundant as in

The newest series of cars from XYZ Motors have redundant brake circuits on all four wheels.

That means they have duplicated the brake circuits so if one circuit is damaged, for example by driving over an obstruction, the car will still stop. As I said, it doesn't mean unnecessary.
 
Aline Galea
Greenhorn
Posts: 22
2
IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you all for the explanations. It's really helpful to know not only how you do things, but also why you do things that way.
 
reply
    Bookmark Topic Watch Topic
  • New Topic