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.
"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
Joined: Jan 29, 2003
Posts: 8791
posted
0
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.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
posted
0
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.
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.