Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructors or accessor/mutator

 
ssiva raman
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which is best way constructors or accessor/mutator to initialize the instance variable of a class.
 
K. Tsang
Bartender
Posts: 3585
16
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no "best" way. It depends on the need or purpose of the class. Normally a simple Java bean will use accessor/mutator. Yet for non-mutable classes, the attributes are set only once during instantiation (in constructor) and only has accessor methods.

 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That depends. It could be either or both. I'd ask the following questions:

- Should it be compulsory for the instance variables to be set? If so, then you should use a constructor.

- Do you need to be able to change the values after they've been set? If so, you need mutators. Don't just add them automatically, though. There are advantages to immutable properties, and you should only make them mutable if they need to be.

 
ssiva raman
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys you both have answers.

if you want to set a immutable data field then set it with constructors or else give accesor/mutator for future change.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic