Recommended Posts

hello,
say i want to create a new instance of a class which has quite a lot of members.
is it better to provide them all as parameters to the constructor or to assign them all as public variables.
example1:

Share this post

Link to post

Share on other sites

I'd limit the constructor args to only necessary items, initialize all the others in the constructor initializer lists to sensible values, and allow the caller to modify them through modifier functions, rather than making them public. Using modifier functions you can validate the input for correctness before setting it and assert or whatever. Public variables if the class is a POD type.

Link to post

Share on other sites

Share this post

Link to post

Share on other sites

Unless it is one of those odd homeworks, just use important arguments for constructors, for example the size of an array the class would use, or if the class seriously requires the path of a file that's a good one too. For the rest use default, dummy values

0

Share this post

Link to post

Share on other sites

On the number of parameters, whether there are sensible values for them, whether they have any logical groupings, whether some can be calculated from others (some may be explicitly intended as caches of precalculated values; others may turn out to be unnecessary upon further reflection), etc.

Share this post

Link to post

Share on other sites

Although its kind of an immature guide, when the parameter list extends past the 80th column, there are probably too many. Same goes for functions and the like. What you should probably confine to the constructor is just the data that makes an object relatively unique. For example, a class containing data about a ball, you'd need it's radius, color, location on the screen. But for this same ball, you probably wouldn't include metadata like which direction its rolling, or how much of a bounce it has to it.