I a beginner to OO-programming, and this question is about handling data validation in a particular design. I have read this thread about a similar problem, and I like the second solution, which recommends re-designing the constructor interface such that invalid values are impossible, but i wonder whether this idea is also applicable to my case. So I have outlined my thoughts below and would like to know if people agree with my ideas.
I have a Die
class, which is constructed by passing a vector of probabilities. All the probabilities must be non-negative, and must add up to 1.0.
class Die
{
public:
Die(/* Probability vector. */);
int Roll();
}
I can think of several options to implement data validation:
The
Die
constructor is protected and accepts anstd::vector<double>
. Then have a static public method that performs the data validation, and returns a pointer to a newDie
object if this is successful, and aNULL
otherwise.Create a
ProbabilityVector
class, which wraps around anstd::vector<double>
, and implement the data validation there (with the protected constructor + public static method above). Then theDie
constructor accepts a (pointer to a)ProbabilityVector
.Implement a separate
ProbabilityVectorValidation
class, with a static method on anstd::vector<double>
returning abool
. Then, when necessary, use this method before passing anstd::vector<double>
to theDie
constructor.
The disadvantage of (1) is that the validation is carried out every time a Die
is created, even though this may not be necessary. (2) gets around this problem, but I'm not sure if the protected constructor + static public approach is elegant, because it involves raw pointers. (3) is looking like an attractive option, but seems less robust than (1) and (2)?