| Author |
referencing fields qualified ?
|
Uwe Schäfer
Ranch Hand
Joined: Mar 15, 2005
Posts: 52
|
|
hi what is your feeling about using "this."-prefix in every access to a class-member ? i feel i�d have to, in order to be consistent with setters i wrote (without event thinking about it) like: or with constants i use but now i see "this." all over the place. good or bad style ?
|
scja|scjp|scjd|scwcd|scbcd|scdjws|scmad
|
 |
Darya Akbari
Ranch Hand
Joined: Aug 21, 2004
Posts: 1855
|
|
Hallo Uwe, here is what Kathy Sierra and Bert Bates say about it:
Avoid shadowing variables. This occurs when an instance variable has the same name as a local or block variable. While the compiler will allow it, shadowing is considered very unfriendly towards the next co-worker (remember: potentially psychopathic) who has to maintain your code.
So better avoid the "this." approach. Regards, Darya
|
SCJP, SCJD, SCWCD, SCBCD
|
 |
Uwe Schäfer
Ranch Hand
Joined: Mar 15, 2005
Posts: 52
|
|
Originally posted by Darya Akbari: So better avoid the "this." approach.
thanks for your answer. this is not necessarily about shadowing variables which is obviously a bad idea most of the time. consider the simple code: i do think that "this." improves readability here, even if it is not really necessary. what do you think ?
|
 |
Frans Janssen
Ranch Hand
Joined: Dec 29, 2004
Posts: 357
|
|
Hi Uwe, My personal preference is to only use this or the class name where it is absolutetely required. And as Darya pointed out already, it is generally good style to avoid the possibility for naming conflicts. I do however make exceptions for trivial setters or constructors, but I must confess that I already had to solve numerous bugs where I mixed up local and class level variables (so maybe I am too easy on myself! ). BTW, in the coding rules we use at the workplace, we have the K&B rule that forbids shadowing. Frans.
|
SCJP 1.4, SCJD
|
 |
Andrew Monkhouse
author and jackaroo
Marshal Commander
Joined: Mar 28, 2003
Posts: 10816
|
|
Hi Uwe, In many ways this is a case of personal preference. If you have a corporate statndard, use it, otherwise find a standard you like, and stick to it . Personally I like the 'this.' prefix - it makes it clear that we are talking about a class variable, which can be useful for the next person to maintain your code (or even for yourself when you revisit the code 6 months later). I have noticed that many of the automatic code generators use the 'this.' prefix when referring to class variables - presumably to help humans read it (since auto generated code should be correct). Regards, Andrew
|
The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
|
 |
 |
|
|
subject: referencing fields qualified ?
|
|
|