Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a constructor, what should I prefer:



or this



Where is the difference?
 
K. Tsang
Bartender
Posts: 3521
16
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Campbell Ritchie
Sheriff
Pie
Posts: 50248
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic