Is it better to use constructors with parameters to initialize the members of a class or do that indirectly using setter functions? I did not get a clear answer on this question so far. Any insights would be appreciated.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is almost certainly a matter of design choice or sometimes style. I would consider a number of things:
Would constructing an object without setting the member variables leave the class in an invalid state? If so, you’ll need your constructor to take valid values for those members. Otherwise, you should be able to provide useful defaults.
Would setting individual members of variables violate a class invariant? If so, they should not have their own setters.
Is the user of this class likely to want to modify individual members? If so, then setters may be appropriate.
Does it make conceptual sense to be able to change individual members of an object? I would argue that it makes no sense to be able to change a
Person‘s date of birth. However, you could argue that changing aPerson‘s name does make sense. It depends. Do you consider aPersonwhose name has changed to be a differentPersonin your system?Can you group setters together to be more useful? Instead of
Rectangle::setX(int)andRectangle::setY(int), doesRectangle::setPosition(int,int)make more sense? Perhaps evenRectangle::setPosition(Point)is better.In any case, a class whose full set of members are exposed through individual setters and getters is usually a code smell.