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

Constructors and setter calls

 
John Dell'Oso
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

Just a quick concept question. Are there any opinions out there with regards to constuctors calling its own class setter methods to initialise its instance fields?

I've recently used this technique a couple of times and I have had no issues with it. It works quite well as I can keep all my validation code in the setters and call the setters from the constructors as required.

Any thoughts on whether this is a good or bad approach would be appreciated.

Thanks.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Wayne Carey",
as a fellow Australian, I suspect your display name is fictitious. Unfortunately the JavaRanch display name rules do not allow fictitious names. Can you please edit your profile and select a valid name.

Accounts with invalid diaplay names get deleted, often without warning

thanks,
Dave.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructor calling set methods (and other methods) should be fine. Be careful that constructor code does not pass "this" to any other object that might try to use it. "this" is not necessarily valid for use yet during the constructor.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Typically, I design my classes to be immutable. In otherwords, I avoid setter methods as often as possible. This is more of a design decision that an implementation issue. If you decide to use setters, I think you have a good idea with calling them from your constructor.

Layne
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the constructor, if you are going to invoke an instance method of the object being constructed, may it be a private method. If it is not a private method, may it be a final method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic