| Author |
constructor
|
nimo frey
Ranch Hand
Joined: Jun 28, 2008
Posts: 580
|
|
In a constructor, what should I prefer:
or this
Where is the difference?
|
 |
K. Tsang
Ranch Hand
Joined: Sep 13, 2007
Posts: 1222
|
|
If setProp is a method in that class then there really is no difference. For version 1 the "this" is not needed. The version 2 is useful if the class is NOT a JavaBean (meaning does have get/set methods ONLY).
|
K. Tsang JavaRanch SCJP5 SCJD/OCM-JD
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32689
|
|
If you use the first format, the method called should have private access or a final modifier. So I would prefer the second.
Beware: if you use a class called "Const" there is a risk of using the keyword "const" by mistake.
|
 |
Brian Legg
Ranch Hand
Joined: Nov 07, 2008
Posts: 488
|
|
|
I would prefer the first option. You have no idea what prop is equal to when it is passed to your constructor but you immediately set this.prop equal to it. Maybe this isn't an issue, but lets say that you are expecting prop to be between 0 and 500 or some other constraint. By passing the value to setProp() method you can check the value to make sure it is valid before setting this.prop equal to it. Yes, you could do the same thing in your constructor but if setProp() is a public method then you will have duplicate code which is always frowned upon. Assuming you don't care what prop is and/or your setProp() method is either not public or contains no logic then either choice is fine.... otherwise option 1 is the best IMHO.
|
SCJA
~Currently preparing for SCJP6
|
 |
Saifuddin Merchant
Ranch Hand
Joined: Feb 08, 2009
Posts: 576
|
|
Seems more a matter of style generally - Brian brought up a suitable point and in the case he mentions his logic makes perfect sense!
I'd prefer the second just because I more used to it ...
|
Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
|
 |
 |
|
|
subject: constructor
|
|
|